Save a PNG to a stream
I can't figure out what is wrong with the following function. It is
supposed to take the given image object and use it to save the image
it contains to a stream. The information from the stream will be
transferred to an HGLOBAL for the calling function to use.
All of the above really doesn't matter. I just thought I would fill
you in. The problem is that the function works fine on a jpeg format
(indicated by the encoder parameter) however if I pass in "image/png"
for the encoder value, the image will not save. It fails and sometimes
I get a value of 10 (file not found) or "undefined value" in the
Status variable. I'm completely stuck on this. My boss still insists
on using c++ and mfc, and most all documentation I've found on GDI+
has been in the form of .net and c#
If you have any idea your help would be greatly appreciated.
HGLOBAL GetImageBlob(Image *pImage, CString encoder)
{
IStream *imageStream;
HRESULT hr = ::CreateStreamOnHGlobal (NULL, FALSE, &imageStream);
CLSID clsid;
GetEncoderClsid((WCHAR *) encoder.GetString(), &clsid);
Status s = pImage->Save(imageStream, &clsid);//Problem
line.....................
STATSTG stats;
imageStream->Stat(&stats, 0);
HGLOBAL hBuf = GlobalAlloc(GMEM_ZEROINIT | GMEM_FIXED,
stats.cbSize.QuadPart);
unsigned char *pBuf = (unsigned char *) GlobalLock(hBuf);
LARGE_INTEGER disp;
disp.QuadPart = 0;
unsigned long read = 0;
imageStream->Seek(disp, STREAM_SEEK_SET, NULL);
imageStream->Read(pBuf, stats.cbSize.QuadPart, &read);
return hBuf;
}
//Helper function found on msdn.com that is supposed to get the class
id of the requested image encoder.
int GetEncoderClsid(const WCHAR* format, CLSID* pClsid)
{
UINT num = 0; // number of image encoders
UINT size = 0; // size of the image encoder array in bytes
ImageCodecInfo* pImageCodecInfo = NULL;
GetImageEncodersSize(&num, &size);
if(size == 0)
return -1; // Failure
pImageCodecInfo = (ImageCodecInfo*)(malloc(size));
if(pImageCodecInfo == NULL)
return -1; // Failure
GetImageEncoders(num, size, pImageCodecInfo);
for(UINT j = 0; j < num; ++j)
{
if( wcscmp(pImageCodecInfo[j].MimeType, format) == 0 )
{
*pClsid = pImageCodecInfo[j].Clsid;
free(pImageCodecInfo);
return j; // Success
}
}
free(pImageCodecInfo);
return -1; // Failure
}