说明 : 因为BMP图片是从下往上,从左往右存储的,所以RGB数据写入BMP数据里要倒过来取。
如里把RGB从左往右,从上往下存储,那么bmp头就要把高度写成负数。
例:
var bytes = .... ; //RGB byte 数据
var fileSize = bytes.length +14 + 40;
console.log("fileSize:"+fileSize);
var nBytes = new Uint8Array(fileSize);
var width = (w == null ) ? 320 : w; // w是RGB图片的宽度
// var height = (h == null ) ? 0xffffffff - 240 + 1 : h; // 倒转正 ,h是RGB图片的高度
var height = (h == null ) ? 240 : h; // h是RGB图片的高度
//top
nBytes[0] = 0x42;//2Bytes,必须为"BM",即0x424D 才是Windows位图文件
nBytes[1] = 0x4D;
nBytes[2] = fileSize % 256;//4Bytes,整个BMP文件的大小
nBytes[3] = fileSize / 256 % 256;
nBytes[4] = fileSize / 256 / 256 % 256;
nBytes[5] = fileSize / 256 / 256 /256 % 256;
nBytes[6] = 0;//2Bytes,保留,为0
nBytes[7] = 0;
nBytes[8] = 0;//2Bytes,保留,为0
nBytes[9] = 0;
nBytes[10] = 0x36; //4Bytes,文件起始位置到图像像素数据的字节偏移量
nBytes[11] = 0;
nBytes[12] = 0;
nBytes[13] = 0;
nBytes[14] = 0x28; //4Bytes,INFOHEADER结构体大小,存在其他版本I NFOHEADER,用作区分
nBytes[15] = 0;
nBytes[16] = 0;
nBytes[17] = 0;
nBytes[18] = width % 256; //4Bytes 宽
nBytes[19] = width / 256 % 256;
nBytes[20] = width / 256 / 256 % 256;
nBytes[21] = width / 256 / 256 /256 % 256;
nBytes[22] = height % 256; //4Bytes 高
nBytes[23] = height / 256 % 256;
nBytes[24] = height / 256 / 256 % 256;
nBytes[25] = height / 256 / 256 /256 % 256;
nBytes[26] = 0x01;//图像数据平面,BMP存储RGB数据,因此总为1
nBytes[27] = 0x00;
nBytes[28] = 0x18;//图像像素位数
nBytes[29] = 0x00;
nBytes[30] = 0x00;//0:不压缩,1:RLE8,2:RLE4
nBytes[31] = 0x00;
nBytes[32] = 0x00;
nBytes[33] = 0x00;
nBytes[34] =parseInt( width * height * 3) % 256;//RGB内容大小
nBytes[35] =parseInt(( width * height * 3) / 256) % 256;
nBytes[36] =parseInt(( width * height * 3) / 256 / 256) % 256;
nBytes[37] =parseInt(( width * height * 3) / 256 / 256 /256) % 256;
// nBytes[34] = 0x00;//RGB内容大小
// nBytes[35] = 0x84;
// nBytes[36] = 0x03;
// nBytes[37] = 0x00;
nBytes[38] = 0x60;//4 Bytes,用象素/米表示的水平分辨率
nBytes[39] = 0x00;
nBytes[40] = 0x00;
nBytes[41] = 0x00;
nBytes[42] = 0x60;//4 Bytes,用象素/米表示的垂直分辨率
nBytes[43] = 0x00;
nBytes[44] = 0x00;
nBytes[45] = 0x00;
nBytes[46] = 0x00;//4 Bytes,实际使用的调色板索引数,0:使用所有的调色板索引
nBytes[47] = 0x00;
nBytes[48] = 0x00;
nBytes[49] = 0x00;
nBytes[50] = 0x00;//4 Bytes,重要的调色板索引数,0:所有的调色板索引都重要
nBytes[51] = 0x00;
nBytes[52] = 0x00;
nBytes[53] = 0x00;
// for(var i = 0 ; i < bytes.length ; i ++){ // 倒转正
// nBytes[54 + i] = bytes[i];
// }
var a = 0 ;
for(var i = 0 ; i < height ; i ++){
for(var j = 0 ; j < width * 3 ; j ++ ){
nBytes[54 + a] = bytes[bytes.length - (width * 3 * i) - (width * 3 - j)];
a ++ ;
}
}
return nBytes;//返回BMP文件数据