将数据块保存为BMP图片函数

#define BMP_Header_Length 54
// 写入bmp文件(24位)
int save_bmp_image(int w, int h, unsigned char *pdata, char *BmpFileName, int IsRGBA )
{
    int ret = 0;
    
    unsigned char header[BMP_Header_Length] = {

        0x42, 0x4d, 0, 0, 0, 0, 0, 0, 0, 0,

            54, 0, 0, 0, 40, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, IsRGBA ? 32 : 24, 0,

            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,

            0, 0, 0, 0

    };

    long file_size = (long)w * (long)h * (IsRGBA ? 4 : 3) + 54;

    header[2] = (unsigned char)(file_size &0x000000ff);
    header[3] = (file_size >> 8) & 0x000000ff;
    header[4] = (file_size >> 16) & 0x000000ff;
    header[5] = (file_size >> 24) & 0x000000ff;
    long width = w;
    header[18] = width & 0x000000ff;
    header[19] = (width >> 8) &0x000000ff;
    header[20] = (width >> 16) &0x000000ff;
    header[21] = (width >> 24) &0x000000ff;
    long height = h;
    header[22] = height &0x000000ff;
    header[23] = (height >> 8) &0x000000ff;
    header[24] = (height >> 16) &0x000000ff;
    header[25] = (height >> 24) &0x000000ff;

    FILE *pWritingFile = NULL;

    pWritingFile = fopen(BmpFileName, "wb"); 
    if( pWritingFile == NULL )
    {
        printf("-----------%s:%d-------------- fopen  failed-!\n", __FUNCTION__, __LINE__);
        return -1;
    }

    ret = fwrite(header, sizeof(unsigned char), 54, pWritingFile);
    if(ret < 0)
    {
        printf("-----------%s:%d---ret %d---- fwrite header failed-!\n", __FUNCTION__, __LINE__, ret);
        return -1;
    }
    
    int BytesPerPixel = IsRGBA ? 4 : 3;
    int LineLength, TotalLength; 
    LineLength = w * BytesPerPixel; // 每行数据长度大致为图象宽度乘以 
    
    // 每像素的字节数 
    while( LineLength % 4 != 0 ) // 修正LineLength使其为4的倍数 
        ++LineLength; 
    TotalLength = LineLength * h; // 数据总长 = 每行长度 * 图象高度
    
    ret = fwrite(pdata, sizeof(unsigned char), (size_t)(long)TotalLength,  pWritingFile);
    if(ret < 0)
    {
        printf("-----------%s:%d---ret %d---- fwrite data failed-!\n", __FUNCTION__, __LINE__, ret);
        return -1;
    }
    
    // 释放内存和关闭文件     
    fclose(pWritingFile); 
    
    return 0;
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值