一、準備工作
在開始使用libgdiplus進行圖像處理前,需要先進行一些準備工作。
首先,需要安裝libgdiplus庫。在Linux系統中,可以使用以下命令進行安裝:
sudo apt-get install libgdiplus
在Windows系統中,需要下載對應的二進位文件並進行安裝。
其次,還需要在代碼中引入頭文件,可以使用以下代碼進行引入:
#include <gdiplus.h> #pragma comment (lib,"Gdiplus.lib") using namespace Gdiplus;
二、圖像載入
在使用libgdiplus進行圖像處理之前,需要先將圖像載入到內存中。
可以使用以下代碼進行圖像的載入:
Bitmap* bmp = new Bitmap(L"path/to/image.jpg");
其中,路徑可以是相對路徑或絕對路徑。
三、圖像處理
在圖像載入完成後,可以進行各種圖像處理操作。
四、圖像保存
處理完成後,可以將圖像保存到磁碟中。
可以使用以下代碼進行圖像保存:
bmp->Save(L"path/to/save.jpg", &clsid, NULL);
其中,路徑可以是相對路徑或絕對路徑。clsid是壓縮格式的GUID,可以使用以下代碼進行初始化:
CLSID clsid; GetEncoderClsid(L"image/jpeg", &clsid);
GetEncoderClsid函數可以使用以下代碼進行定義:
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; pImageCodecInfo = (ImageCodecInfo*)(malloc(size)); if(pImageCodecInfo == NULL) return -1; 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; } } free(pImageCodecInfo); return -1; }
五、功能示例
下面是一個使用libgdiplus進行圖像處理的示例代碼,包括圖像旋轉、縮放、裁剪和保存:
#include <iostream> #include <gdiplus.h> #pragma comment (lib,"Gdiplus.lib") using namespace 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; GetImageEncodersSize(&num, &size); if(size == 0) return -1; pImageCodecInfo = (ImageCodecInfo*)(malloc(size)); if(pImageCodecInfo == NULL) return -1; 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; } } free(pImageCodecInfo); return -1; } int main() { GdiplusStartupInput gdiplusStartupInput; ULONG_PTR gdiplusToken; GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL); Bitmap* bmp = new Bitmap(L"test.jpg"); int width = bmp->GetWidth(); int height = bmp->GetHeight(); // rotate RotateFlipType rotateFlipType = Rotate180FlipXY; bmp->RotateFlip(rotateFlipType); // resize int newWidth = width / 2; int newHeight = height / 2; Bitmap* bmpResize = new Bitmap(bmp, newWidth, newHeight); // crop int cropX = newWidth / 2; int cropY = newHeight / 2; int cropWidth = newWidth / 2; int cropHeight = newHeight / 2; Bitmap* bmpCrop = bmpResize->Clone(cropX, cropY, cropWidth, cropHeight, PixelFormatDontCare); // save CLSID clsid; GetEncoderClsid(L"image/jpeg", &clsid); bmpCrop->Save(L"output.jpg", &clsid, NULL); delete bmp; delete bmpResize; delete bmpCrop; GdiplusShutdown(gdiplusToken); return 0; }
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/280372.html