`
hereson3
  • 浏览: 159895 次
  • 性别: Icon_minigender_2
  • 来自: 广州
社区版块
存档分类
最新评论

C语言将raw data(rgb/rgba)写成bmp文件(bmp24或32)

阅读更多

int bmp_write(unsigned char *image, int xsize, int ysize, char *filename)
{
    unsigned char header[54] = {
      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, 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)xsize * (long)ysize * 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 = xsize;
    header[18] = width & 0x000000ff;
    header[19] = (width >> 8) &0x000000ff;
    header[20] = (width >> 16) &0x000000ff;
    header[21] = (width >> 24) &0x000000ff;
  
    long height = ysize;
    header[22] = height &0x000000ff;
    header[23] = (height >> 8) &0x000000ff;
    header[24] = (height >> 16) &0x000000ff;
    header[25] = (height >> 24) &0x000000ff;

    char fname_bmp[128];
    sprintf(fname_bmp, "%s.bmp", filename);
  
    FILE *fp;
    if (!(fp = fopen(fname_bmp, "wb")))
      return -1;
     
    fwrite(header, sizeof(unsigned char), 54, fp);
    fwrite(image, sizeof(unsigned char), (size_t)(long)xsize * ysize * 4(或者3), fp);
  
    fclose(fp);
    return 0;
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics