百度百科關(guān)于BMP文件的格式講的相當(dāng)詳細(xì).還是有注意點(diǎn):
- long 占用的是8個(gè)字節(jié),網(wǎng)上的代碼很多都有問題
- attribute ((packed)) 是1字節(jié)對(duì)齊的意思,如果不加這段代碼生成的圖片就有問題
下面是完整代碼:
typedef int32_t LONG;
typedef uint32_t DWORD;
typedef unsigned short WORD;
typedef struct {
WORD bfType;
DWORD bfSize;
WORD bfReserved1;
WORD bfReserved2;
DWORD bfOffBits;
} __attribute__ ((packed)) BMPFILEHEADER_T;
typedef struct{
DWORD biSize;
LONG biWidth;
LONG biHeight;
WORD biPlanes;
WORD biBitCount;
DWORD biCompression;
DWORD biSizeImage;
LONG biXPelsPerMeter;
LONG biYPelsPerMeter;
DWORD biClrUsed;
DWORD biClrImportant;
} __attribute__ ((packed)) BMPINFOHEADER_T;
void savebmp(uint8_t * pdata, char * bmp_file, int width, int height )
{ //分別為rgb數(shù)據(jù),要保存的bmp文件名,圖片長(zhǎng)寬
int size = width*height*3*sizeof(char); // 每個(gè)像素點(diǎn)3個(gè)字節(jié)
// 位圖第一部分,文件信息
BMPFILEHEADER_T bfh;
bfh.bfType = (WORD)0x4d42; //bm
bfh.bfSize = size // data size
+ sizeof( BMPFILEHEADER_T ) // first section size
+ sizeof( BMPINFOHEADER_T ) // second section size
;
bfh.bfReserved1 = 0; // reserved
bfh.bfReserved2 = 0; // reserved
bfh.bfOffBits = sizeof( BMPFILEHEADER_T )+ sizeof( BMPINFOHEADER_T );//真正的數(shù)據(jù)的位置
// 位圖第二部分,數(shù)據(jù)信息
BMPINFOHEADER_T bih;
bih.biSize = sizeof(BMPINFOHEADER_T);
bih.biWidth = width;
bih.biHeight = -height;//BMP圖片從最后一個(gè)點(diǎn)開始掃描,顯示時(shí)圖片是倒著的,所以用-height,這樣圖片就正了
bih.biPlanes = 1;//為1,不用改
bih.biBitCount = 24;
bih.biCompression = 0;//不壓縮
bih.biSizeImage = size;
bih.biXPelsPerMeter = 2835 ;//像素每米
bih.biYPelsPerMeter = 2835 ;
bih.biClrUsed = 0;//已用過的顏色,24位的為0
bih.biClrImportant = 0;//每個(gè)像素都重要
/* C語言寫法
FILE * fp = fopen( bmp_file,"wb" );
if( !fp ) return;
fwrite( &bfh, 8, 1, fp );//由于linux上4字節(jié)對(duì)齊,而信息頭大小為54字節(jié),第一部分14字節(jié),第二部分40字節(jié),所以會(huì)將第一部分補(bǔ)齊為16自己,直接用sizeof,打開圖片時(shí)就會(huì)遇到premature end-of-file encountered錯(cuò)誤
fwrite(&bfh.bfReserved2, sizeof(bfh.bfReserved2), 1, fp);
fwrite(&bfh.bfOffBits, sizeof(bfh.bfOffBits), 1, fp);
fwrite( &bih, sizeof(BMPINFOHEADER_T),1,fp );
fwrite(pdata,size,1,fp);
fclose( fp );
*/
NSMutableData *dataM = [NSMutableData data];
[dataM appendBytes:&bfh length:14];//由于字節(jié)對(duì)齊問題,此處不能用sizeof
[dataM appendBytes:&bih length:sizeof(BMPINFOHEADER_T)];
[dataM appendBytes:pdata length:size];
// [dataM writeToFile:@"/Users/apple/Desktop/tb.bmp" atomically:YES];
}