ISP/sim/bmp.cpp

46 lines
1.7 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include "bmp.hpp"
#include <fstream>
#include <iostream>
// 将RGB24格式像素数据封装为BMP图像
bool write_bmp(const char* filename, uint8_t* data, int32_t width,
int32_t height) {
BMPFileHeader file_header = {0};
BMPInfoHeader info_header = {0};
std::ofstream ofs(filename, std::ios::binary);
if (!ofs) {
std::cerr << "Failed to create file: " << filename << std::endl;
return false;
}
// BMP文件头
file_header.type = 0x4D42; // BM
file_header.size =
sizeof(BMPFileHeader) + sizeof(BMPInfoHeader) + width * height * 3;
file_header.offset = sizeof(BMPFileHeader) + sizeof(BMPInfoHeader);
ofs.write(reinterpret_cast<char*>(&file_header), sizeof(file_header));
// BMP位图信息头
info_header.size = sizeof(BMPInfoHeader);
info_header.width = width;
info_header.height = height;
info_header.planes = 1;
info_header.bit_count = 24;
info_header.size_image = width * height * 3;
ofs.write(reinterpret_cast<char*>(&info_header), sizeof(info_header));
// 像素数据
int32_t row_size = (((width + 1) * 3) / 4) * 4; // 行字节数必须为4的倍数
uint8_t* row_data = new uint8_t[row_size];
for (int32_t y = height - 1; y >= 0; --y) { // BMP图像的行是从下往上存储的
for (int32_t x = 0; x < width; ++x) {
row_data[x * 3 + 2] = data[(y * width + x) * 3 + 0]; // B
row_data[x * 3 + 1] = data[(y * width + x) * 3 + 1]; // G
row_data[x * 3 + 0] = data[(y * width + x) * 3 + 2]; // R
}
ofs.write(reinterpret_cast<char*>(row_data), row_size);
}
delete[] row_data;
ofs.close();
return true;
}