GDI+ 保存RGB32为bmp C++
时间: 2023-10-28 21:05:52 浏览: 226
下面是使用GDI+保存RGB32为bmp的C++代码示例:
```c++
#include <Windows.h>
#include <gdiplus.h>
#pragma comment(lib, "gdiplus.lib")
using namespace Gdiplus;
void SaveBMP(const WCHAR* filePath, UINT width, UINT height, UINT stride, BYTE* imageData)
{
// 初始化GDI+
GdiplusStartupInput gdiplusStartupInput;
ULONG_PTR gdiplusToken;
GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);
// 创建位图
Bitmap bitmap(width, height, stride, PixelFormat32bppRGB, imageData);
// 保存位图为bmp文件
CLSID clsid;
GetEncoderClsid(L"image/bmp", &clsid);
bitmap.Save(filePath, &clsid, NULL);
// 关闭GDI+
GdiplusShutdown(gdiplusToken);
}
int main()
{
// 假设有一张宽为640,高为480的RGB32格式的图像数据,数据存放在imageData中
UINT width = 640;
UINT height = 480;
UINT stride = width * 4; // 因为是32位色深,所以每个像素占用4个字节
BYTE* imageData = new BYTE[stride * height];
// 保存为bmp文件
SaveBMP(L"test.bmp", width, height, stride, imageData);
// 释放图像数据内存
delete[] imageData;
return 0;
}
```
其中,GetEncoderClsid函数用于获取指定MIME类型的编码器的CLSID:
```c++
int GetEncoderClsid(const WCHAR* mimeType, CLSID* pClsid)
{
UINT num = 0, size = 0;
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 i = 0; i < num; ++i)
{
if (wcscmp(pImageCodecInfo[i].MimeType, mimeType) == 0)
{
*pClsid = pImageCodecInfo[i].Clsid;
free(pImageCodecInfo);
return i;
}
}
free(pImageCodecInfo);
return -1;
}
```
阅读全文