HBITMAP to JPEG /PNG without CImage in C++

回眸只為那壹抹淺笑 提交于 2019-12-02 03:04:40

问题


I've got a HBITMAP that I want to save into a JPEG/PNG stream or array of bytes. The problem is that I'm using mingw as my compiler so I can't use CImage.. which would have made my life easier.

I can get the pixels from the bitmap without any problems, but I have no idea how to get access to them in JPEG/PNG-format.

Where do I start?


回答1:


If you have access DirectX library you may use IStream to convert your image to JPEG http://msdn.microsoft.com/en-us/library/windows/desktop/aa380034(v=vs.85).aspx

or if you have GDI+ something like this might work

Gdiplus::Bitmap bmp(hbmpImage,(HPALETTE)0);
CLSID pngClsid;
GetEncoderClsid(L"image/png", &pngClsid);
bmp.Save(L"D:\image.png",&pngClsid,NULL);

where GetEncoderLCLsid looks like this:

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
}

don't forget to initialize GDI+

 GdiplusStartupInput gdiplusStartupInput;
   ULONG_PTR gdiplusToken;
   GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

if don't have access to either you may use libjpeg but you need to put all the dependencies packages from the GnuWin32 site. Much faster the code in this page should work, just forget about the boost

libjpeg dying without message




回答2:


Another option is to use the WIC API (Windows Imaging Component), which gives direct access to image encoders and decoders. I believe GDI+ may use this under the covers.



来源:https://stackoverflow.com/questions/13554905/hbitmap-to-jpeg-png-without-cimage-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!