#include <iostream>
#include <string>
#include <fstream>
using namespace std;
void write_bmpheader(unsigned char *bitmap, int offset, int bytes, int value)
{
int i;
for (i = 0; i < bytes; i++)
bitmap[offset + i] = (value >> (i << 3)) & 0xFF;
}
int bin2bmp(unsigned char* depth_data, int width, int height, unsigned char *bmp_data)
{
/*create a bmp format file*/
int bitmap_x = width * 3 ;
unsigned char *bitmap = new unsigned char[sizeof(unsigned char)*height*bitmap_x + 54];
bitmap[0] = 'B';
bitmap[1] = 'M';
write_bmpheader(bitmap, 2, 4, height*bitmap_x + 54); //whole file size
write_bmpheader(bitmap, 0xA, 4, 54); //offset before bitmap raw data
write_bmpheader(bitmap, 0xE, 4, 40); //length of bitmap info header
write_bmpheader(bitmap, 0x12, 4, width); //width
write_bmpheader(bitmap, 0x16, 4, height); //height
write_bmpheader(bitmap, 0x1A, 2, 1);
write_bmpheader(bitmap, 0x1C, 2, 24); //bit per pixel
write_bmpheader(bitmap, 0x1E, 4, 0); //compression
write_bmpheader(bitmap, 0x22, 4, height*bitmap_x); //size of bitmap raw data
for (int i = 0x26; i < 0x36; i++)
bitmap[i] = 0;
int k = 54;
for (int i = height - 1; i >= 0; i--)
{
for (int j = 0; j < width; j++)
{
for(int p = 0; p < 3; p++)
{
char depthValue = (char)depth_data[(i * width + j)*3 + p];
bitmap[k++] = depthValue;
}
}
}
memcpy(bmp_data, bitmap, sizeof(unsigned char)*k);
delete[] bitmap;
return 0;
}
int main()
{
int width = 640, height = 400;
// 读取bin文件
string file_name = "./img.bin";
FILE *fp_ptr;
fp_ptr = fopen(file_name.c_str(), "rb");
if (fp_ptr == NULL){
printf("fopen error!\n");
return -1;
}
fclose(fp_ptr);
fseek(fp_ptr, 0, SEEK_SET);
// 申请数据内存
unsigned char *depth_data = new unsigned char[width*height*3];
unsigned char *bmp_data = new unsigned char[sizeof(unsigned char)*height*width * 3 + 54];
bin2bmp(depth_data, width, height,bmp_data);
// 保存bmp文件
FILE *fp = fopen("./img.bmp", "wb+");
if (fp == NULL)
{
cout << "Could not open" << endl;
delete[] depth_data;
delete[] bmp_data;
return -1;
}
fwrite(bmp_data, 1, sizeof(unsigned char)*height*width * 3 + 54, fp);
fclose(fp);
delete[] depth_data;
delete[] bmp_data;
return 0;
}
二进制流转bmp数据
最新推荐文章于 2022-04-25 18:40:32 发布