也不用这种方法
时间: 2024-01-31 13:03:22 浏览: 19
除了 GDI+ 和 OpenCV 之外,还可以使用 C++ 标准库来保存 BMP 图像。示例代码如下:
```c++
#include <fstream>
#include <vector>
struct BMPHeader {
uint16_t type;
uint32_t size;
uint16_t reserved1;
uint16_t reserved2;
uint32_t offset;
uint32_t dib_header_size;
int32_t width;
int32_t height;
uint16_t planes;
uint16_t bpp;
uint32_t compression;
uint32_t image_size;
int32_t x_ppm;
int32_t y_ppm;
uint32_t colors;
uint32_t important_colors;
};
void SaveBitmapToFile(const char* szFileName, const uint8_t* data, int width, int height)
{
std::ofstream out(szFileName, std::ios::binary);
if (!out) return;
BMPHeader header = { 0 };
header.type = 0x4d42;
header.size = width * height * 3 + sizeof(header);
header.offset = sizeof(header);
header.dib_header_size = 40;
header.width = width;
header.height = height;
header.planes = 1;
header.bpp = 24;
header.compression = 0;
header.image_size = 0;
header.x_ppm = 0;
header.y_ppm = 0;
header.colors = 0;
header.important_colors = 0;
out.write(reinterpret_cast<const char*>(&header), sizeof(header));
std::vector<uint8_t> row_data(width * 3);
for (int y = height - 1; y >= 0; --y) {
const uint8_t* row_ptr = data + y * width * 3;
for (int x = 0; x < width; ++x) {
row_data[x * 3 + 2] = row_ptr[x * 3 + 0];
row_data[x * 3 + 1] = row_ptr[x * 3 + 1];
row_data[x * 3 + 0] = row_ptr[x * 3 + 2];
}
out.write(reinterpret_cast<const char*>(row_data.data()), row_data.size());
}
}
```
使用方法:
```c++
int width = ...; // 图像宽度
int height = ...; // 图像高度
std::vector<uint8_t> data = ...; // 图像数据
SaveBitmapToFile("test.bmp", data.data(), width, height); // 保存为 BMP 文件
```
需要注意的是,这种方法需要手动构造 BMP 头部并逆序写入每一行的像素数据。虽然这种方法相对麻烦,但是可以避免依赖第三方库。