title: How to convert CImage to Base64 string in MFC C++
body: <p>I'm porting some code from C# to C++ with MFC and one thing have stopped me. The original code generated an image and then encoded it as a base64 string to use for en embedded image when generating an HTML file.</p>
  <p>The original code first converts it to a byte array</p>
  <pre><code>private byte[] AsBytes(System.Drawing.Image image)
  {
        using (var ms = new System.IO.MemoryStream())
        {
             image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
             return ms.ToArray();
        }
  }
  </code></pre>
  <p>The conversion to Base64 is then a simple call, <code>Convert.ToBase64String(pictureAsBytes)</code> for MFC there is <code>Base64Encode</code> while not as nice it appears to do the job. The problem is going from CImage to CByteArray (or something else useful).</p>
  <p>The code I have causes a lot of headache, but it looks like</p>
  <pre><code>AsBytes(CImage &amp;image, CByteArray &amp;bytes)
  {
      int pitch = image.GetPitch();
      int size = abs(pitch) * image.GetHeight();
      const BYTE *src = (BYTE *)image.GetBits();
  
      if(pitch &lt; 0)
      {
          src -= size;
      }
      
      BYTE *pBitmapData = new BYTE[size];
      memcpy(pBitmapData, src, size * sizeof(BYTE));
  
      for(int i = 0; i &lt; size; i++)
      {
          bytes.Add(pBitmapData[i]);
      }
  }
  </code></pre>