之前寫了一篇《VC++使用CImage在內存中Jpeg轉換Bmp圖片》,通過CImage實現了在內存中Jpeg轉Bmp。
既然Jpeg能轉Bmp,那CImage也支持Bmp轉Jpeg,與上一篇文章依賴CImage的Load函數相反,Bmp轉Jpeg通過Save函數實現:
使用的也是IStream接口的函數重載,具體可以參考MSDN:http://msdn.microsoft.com/zh-cn/library/d06f3fhw.aspx
下面貼出使用CImage在內存中Bmp轉換Jpeg的代碼:
unsigned long BMP2JPEG(char* pUnZipData,unsigned long ulUnZipDataLen,char** pBuffer) { unsigned long ulBufferLen = 0; HGLOBAL hGlobal = GlobalAlloc(GMEM_MOVEABLE, ulUnZipDataLen); void* pData = GlobalLock(hGlobal); memcpy(pData, pUnZipData, ulUnZipDataLen); GlobalUnlock(hGlobal); IStream* pStream = NULL; if(CreateStreamOnHGlobal(hGlobal, TRUE, & pStream) == S_OK) { CImage image; if (SUCCEEDED(image.Load(pStream))) { IStream* pOutStream = NULL; if(CreateStreamOnHGlobal(NULL, TRUE, & pOutStream) == S_OK) { image.Save(pOutStream, Gdiplus::ImageFormatJPEG); HGLOBAL hOutGlobal= NULL; GetHGlobalFromStream(pOutStream,&hOutGlobal); LPBYTE pBits= (LPBYTE)GlobalLock(hOutGlobal); ulBufferLen =(DWORD)GlobalSize(pBits); *pBuffer = new char[ulBufferLen]; memcpy(*pBuffer, pBits, ulBufferLen); GlobalUnlock(hOutGlobal); pOutStream->Release(); } } pStream->Release(); } GlobalFree(hGlobal); return ulBufferLen; }
記錄,為更好的自己!