title: How can I create a Base64-Encoded string from a GDI+ Image in C++?
body: <p>I asked a question recently, <em><a href="https://stackoverflow.com/questions/2746855/how-can-i-create-an-image-in-gdi-from-a-base64-encoded-string-in-c">How can I create an Image in GDI+ from a Base64-Encoded string in C++?</a></em>, which got a response that led me to the answer.</p>
  
  <p>Now I need to do the opposite - I have an Image in GDI+ whose image data I need to turn into a Base64-Encoded string. Due to its nature, it's not straightforward.</p>
  
  <p>The crux of the issue is that an Image in GDI+ can save out its data to either a file or an IStream*. I don't want to save to a file, so I need to use the resulting stream. Problem is, this is where my knowledge breaks down. </p>
  
  <p>This first part is what I figured out in the other question</p>
  
  <pre><code>// Initialize GDI+.
  GdiplusStartupInput gdiplusStartupInput;
  ULONG_PTR gdiplusToken;
  GdiplusStartup(&amp;gdiplusToken, &amp;gdiplusStartupInput, NULL);
  
  // I have this decode function from elsewhere
  std::string decodedImage = base64_decode(Base64EncodedImage);
  
  // Allocate the space for the stream
  DWORD imageSize = decodedImage.length();
  HGLOBAL hMem = ::GlobalAlloc(GMEM_MOVEABLE, imageSize);
  LPVOID pImage = ::GlobalLock(hMem);    
  memcpy(pImage, decodedImage.c_str(), imageSize);
  
  // Create the stream
  IStream* pStream = NULL;
  ::CreateStreamOnHGlobal(hMem, FALSE, &amp;pStream);
  
  // Create the image from the stream
  Image image(pStream);
  
  // Cleanup
  pStream-&gt;Release();
  GlobalUnlock(hMem);
  GlobalFree(hMem);
  </code></pre>
  
  <p>(<a href="https://stackoverflow.com/questions/180947/base64-decode-snippet-in-c">Base64 code</a>)</p>
  
  <p>And now I'm going to perform an operation on the resulting image, in this case rotating it, and now I want the Base64-equivalent string when I'm done.</p>
  
  <pre><code>// Perform operation (rotate)
  image.RotateFlip(Gdiplus::Rotate180FlipNone);
  
  IStream* oStream = NULL;
  
  CLSID tiffClsid;
  GetEncoderClsid(L"image/tiff", &amp;tiffClsid);  // Function defined elsewhere
  image.Save(oStream, &amp;tiffClsid);
  
  // And here's where I'm stumped. 
  </code></pre>
  
  <p>(<a href="http://msdn.microsoft.com/en-us/library/ms533843%28VS.85%29.aspx" rel="nofollow noreferrer">GetEncoderClsid</a>)</p>
  
  <p>So what I wind up with at the end is an IStream* object. But here's where both my knowledge and Google break down for me. IStream shouldn't be an object itself, it's an interface for other types of streams. I'd go down the road from getting string->Image in reverse, but I don't know how to determine the size of the stream, which appears to be key to that route. </p>
  
  <p>How can I go from an IStream* to a string (which I will then Base64-Encode)? Or is there a much better way to go from a GDI+ Image to a string?</p>