---
title: "C语言将raw data(rgb/rgba)写成bmp文件(bmp24或32)"
author: "hereson3"
date: "2009-02-09T17:44:24Z"
tags: []
slug: "c-raw-data-rgb-rgba-bmp-bmp24-32"
draft: false
lastmod: "2009-02-09T17:44:24Z"
id: 325819
url: "https://kungsoft.iteye.com/blog/325819"
---

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 &gt;&gt; 8) & 0x000000ff;  
    header\[4] = (file\_size &gt;&gt; 16) & 0x000000ff;  
    header\[5] = (file\_size &gt;&gt; 24) & 0x000000ff;  
    
    long width = xsize;  
    header\[18] = width & 0x000000ff;  
    header\[19] = (width &gt;&gt; 8) &0x000000ff;  
    header\[20] = (width &gt;&gt; 16) &0x000000ff;  
    header\[21] = (width &gt;&gt; 24) &0x000000ff;  
    
    long height = ysize;  
    header\[22] = height &0x000000ff;  
    header\[23] = (height &gt;&gt; 8) &0x000000ff;  
    header\[24] = (height &gt;&gt; 16) &0x000000ff;  
    header\[25] = (height &gt;&gt; 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;  
}