引言:通過GDI+我們可以很方便的對bmp、jpeg、gif、tiff、png格式的圖片進行轉換。
步驟:
1) 通過GdiplusStartup初始化GDI+,以便後續的GDI+函數可以成功調用。
2) 通過GetImageEncodersSize獲取GDI+支持的圖像格式編碼器種類數numEncoders以及ImageCodecInfo數組的存放大小size。
3) 通過malloc爲ImageCodecInfo數組分配足額空間。
4) 通過GetImageDecoders獲取所有的圖像編碼器信息。
5) 查看ImageCodecInfo.MimeType,查找符合的圖像編碼器的Clsid。
6) 釋放步驟3)分配的內存。
7) 創建Image對象並加載圖片。
8) 調用Image.Save方法進行圖片格式轉換,並把步驟3)得到的圖像編碼器Clsid傳遞給它。
9) 釋放Image對象。
10) 通過GdiplusShutdown清理所有GDI+資源。
示例:
- #include <windows.h>
- #include <gdiplus.h>
- #include <stdio.h>
- using namespace Gdiplus;
- #pragma comment(lib,"gdiplus")
- 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;
- //2.獲取GDI+支持的圖像格式編碼器種類數以及ImageCodecInfo數組的存放大小
- GetImageEncodersSize(&num, &size);
- if(size == 0)
- return -1; // Failure
- //3.爲ImageCodecInfo數組分配足額空間
- pImageCodecInfo = (ImageCodecInfo*)(malloc(size));
- if(pImageCodecInfo == NULL)
- return -1; // Failure
- //4.獲取所有的圖像編碼器信息
- GetImageEncoders(num, size, pImageCodecInfo);
- //5.查找符合的圖像編碼器的Clsid
- for(UINT j = 0; j < num; ++j)
- {
- if( wcscmp(pImageCodecInfo[j].MimeType, format) == 0 )
- {
- *pClsid = pImageCodecInfo[j].Clsid;
- free(pImageCodecInfo);
- return j; // Success
- }
- }
- //6.釋放步驟3分配的內存
- free(pImageCodecInfo);
- return -1; // Failure
- }
- INT main()
- {
- GdiplusStartupInput gdiplusStartupInput;
- ULONG_PTR gdiplusToken;
- //1.初始化GDI+,以便後續的GDI+函數可以成功調用
- GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);
- CLSID encoderClsid;
- Status stat;
- //7.創建Image對象並加載圖片
- Image* image = new Image(L"f://11.bmp");
- // Get the CLSID of the PNG encoder.
- GetEncoderClsid(L"image/png", &encoderClsid);
- //8.調用Image.Save方法進行圖片格式轉換,並把步驟3)得到的圖像編碼器Clsid傳遞給它
- stat = image->Save(L"11.png", &encoderClsid, NULL);
- if(stat == Ok)
- printf("Bird.png was saved successfully/n");
- else
- printf("Failure: stat = %d/n", stat);
- //9.釋放Image對象
- delete image;
- //10.清理所有GDI+資源
- GdiplusShutdown(gdiplusToken);
- return 0;
- }
學習資源:
MSDN -> Win32 和 COM開發 -> Graghics and Multimedia -> GDI+ -> Using GDI+ -> Using Image Encoders and Decoders。