How can I create an Image in GDI+ from a Base64-Encoded string in C++?

前端 未结 2 700
日久生厌
日久生厌 2020-12-19 11:26

I have an application, currently written in C#, which can take a Base64-encoded string and turn it into an Image (a TIFF image in this case), and vice versa. In C# this is a

相关标签:
2条回答
  • 2020-12-19 11:56

    This should be a two-step process. Firstly, decode the base64 into pure binary (the bits you would have had if you loaded the TIFF from file). The first Google result for this looks to be pretty good.

    Secondly, you'll need to convert those bits to a Bitmap object. I followed this example when I had to load images from a resource table.

    0 讨论(0)
  • 2020-12-19 12:00

    OK, using the info from the Base64 decoder I linked and the example Ben Straub linked, I got it working

    using namespace Gdiplus; // Using GDI+
    
    Graphics graphics(hdc); // Get this however you get this
    
    std::string encodedImage = "<Your Base64 Encoded String goes here>";
    
    std::string decodedImage = base64_decode(encodedImage); // using the base64 
                                                            // library I linked
    
    DWORD imageSize = decodedImage.length();
    HGLOBAL hMem = ::GlobalAlloc(GMEM_MOVEABLE, imageSize);
    LPVOID pImage = ::GlobalLock(hMem);
    memcpy(pImage, decodedImage.c_str(), imageSize);
    
    IStream* pStream = NULL;
    ::CreateStreamOnHGlobal(hMem, FALSE, &pStream);
    
    Image image(pStream);
    
    graphics.DrawImage(&image, destRect);
    
    pStream->Release();
    GlobalUnlock(hMem);
    GlobalFree(hMem);
    

    I'm sure it can be improved considerably, but it works.

    0 讨论(0)
提交回复
热议问题