二进制流转bmp数据

#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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值