保存BMP格式圖片API

#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;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章