bitmap 保存bmp
时间: 2023-08-18 17:04:13 浏览: 167
要将位图保存为 BMP 格式,可以使用以下步骤:
1. 创建一个 BITMAPFILEHEADER 结构体,用于保存 BMP 文件头信息。
2. 创建一个 BITMAPINFOHEADER 结构体,用于保存位图信息头。
3. 计算位图像素数据的大小,用于分配内存。
4. 将位图像素数据按照 BMP 文件格式存储到内存中。
5. 将 BITMAPFILEHEADER 和 BITMAPINFOHEADER 写入 BMP 文件开头。
6. 将位图像素数据写入 BMP 文件中。
以下是一个示例代码,用于将位图保存为 BMP 格式:
```c++
#include <fstream>
#include <iostream>
#include <vector>
#include <cstring>
using namespace std;
#pragma pack(push, 1)
// BMP 文件头
typedef struct {
uint16_t bfType; // 文件类型,必须为 BM
uint32_t bfSize; // 文件大小,单位为字节
uint16_t bfReserved1; // 保留字段,必须为 0
uint16_t bfReserved2; // 保留字段,必须为 0
uint32_t bfOffBits; // 位图数据的起始位置,单位为字节
} BITMAPFILEHEADER;
// BMP 位图信息头
typedef struct {
uint32_t biSize; // 信息头大小,必须为 40
int32_t biWidth; // 图像宽度,单位为像素
int32_t biHeight; // 图像高度,单位为像素
uint16_t biPlanes; // 位平面数,必须为 1
uint16_t biBitCount; // 每像素位数,一般为 24
uint32_t biCompression; // 压缩方式,一般为 0
uint32_t biSizeImage; // 图像数据大小,单位为字节
int32_t biXPelsPerMeter; // 水平分辨率,单位为像素/meter
int32_t biYPelsPerMeter; // 垂直分辨率,单位为像素/meter
uint32_t biClrUsed; // 颜色数,一般为 0
uint32_t biClrImportant; // 重要颜色数,一般为 0
} BITMAPINFOHEADER;
#pragma pack(pop)
// 将位图保存为 BMP 格式
bool save_bitmap(const char *filename, const uint8_t *data, int width, int height) {
// 计算位图像素数据大小
int data_size = width * height * 3;
// 创建 BMP 文件头
BITMAPFILEHEADER file_header;
memset(&file_header, 0, sizeof(file_header));
file_header.bfType = 0x4D42; // "BM"
file_header.bfSize = sizeof(file_header) + sizeof(BITMAPINFOHEADER) + data_size;
file_header.bfOffBits = sizeof(file_header) + sizeof(BITMAPINFOHEADER);
// 创建 BMP 位图信息头
BITMAPINFOHEADER info_header;
memset(&info_header, 0, sizeof(info_header));
info_header.biSize = sizeof(info_header);
info_header.biWidth = width;
info_header.biHeight = height;
info_header.biPlanes = 1;
info_header.biBitCount = 24;
info_header.biSizeImage = data_size;
// 打开文件并写入 BMP 文件头和位图信息头
ofstream outfile(filename, ios::binary);
if (!outfile) {
cerr << "Failed to open file: " << filename << endl;
return false;
}
outfile.write(reinterpret_cast<const char*>(&file_header), sizeof(file_header));
outfile.write(reinterpret_cast<const char*>(&info_header), sizeof(info_header));
// 写入位图像素数据
outfile.write(reinterpret_cast<const char*>(data), data_size);
outfile.close();
return true;
}
```
这个函数需要传入一个指向位图像素数据的指针,以及位图的宽度和高度。函数会将位图保存为 BMP 格式,并返回一个布尔值表示保存是否成功。
阅读全文
相关推荐















