我正在使用可生成120x160图像的相机,并将其另存为BMP文件。
我使用的代码的问题在于每个像素的位数,因为相机提供的像素为2个字节(位图[28] = 16),但是当我打开图像时,它告诉我格式为错误的一件事,奇怪的是,如果我放入1个字节(位图[28] = 8),我会得到正确的图像,但是色彩失真有些奇怪,我不知道出了什么问题,希望有人可以帮助我看到我的错误并向他学习。
int noColor=256,end_color=54+4*noColor;
static unsigned char temp=0;
// -- FILE HEADER -- //
// bitmap signature
bitmap[0] = 'B';
bitmap[1] = 'M';
// file size
bitmap[2] = 0x36; // 40 + 14 + 256*4+(120x160)
bitmap[3] = 0x4F;
bitmap[4] = 0x00;
bitmap[5] = 0;
// reserved field (in hex. 00 00 00 00)
for( i = 6; i < 10; i++) bitmap[i] = 0;
// offset of pixel data inside the image
//The offset, i.e. starting address, of the byte where the bitmap image data (pixel array) can be found.
//here 1078
bitmap[10]=0x36;
bitmap[11]=0x04;
for( i = 12; i < 14; i++) bitmap[i] = 0;
// -- BITMAP HEADER -- //
// header size
bitmap[14] = 40;
for( i = 15; i < 18; i++) bitmap[i] = 0;
// width of the image
bitmap[18] = 160;
for( i = 19; i < 22; i++) bitmap[i] = 0;
// height of the image
bitmap[22] = 120;
for( i = 23; i < 26; i++) bitmap[i] = 0;
// no of color planes, must be 1
bitmap[26] = 1;
bitmap[27] = 0;
// number of bits per pixel
bitmap[28] =16; // 2 byte
bitmap[29] = 0;
// compression method (no compression here)
for( i = 30; i < 34; i++) bitmap[i] = 0;
// size of pixel data
bitmap[34] = 0x00; // (120*160) bytes => 19200 pixels--->0x4B00
bitmap[35] = 0x4B;//0x4B
bitmap[36] = 0x00;
bitmap[37] = 0;
// horizontal resolution of the image - pixels per meter (2835)
bitmap[38] = 0;
bitmap[39] = 0;
bitmap[40] = 0;
bitmap[41] = 0;
// vertical resolution of the image - pixels per meter (2835)
bitmap[42] = 0;
bitmap[43] = 0;
bitmap[44] = 0;
bitmap[45] = 0;
// color palette information here 256
bitmap[46]=0;
bitmap[47]=0;
for( i = 48; i < 50; i++) bitmap[i] = 0;
// number of important colors
// if 0 then all colors are important
for( i = 50; i < 54; i++) bitmap[i] = 0;
//Color Palette
//for less then or equal to 8 bit BMP Image we have to create a 4*noofcolor size color palette which is nothing but
//[BLUE][GREEN][RED][ZERO] values
//for 8 bit we have the following code
for (i=54;i<end_color;i+=4)
{
bitmap[i]=temp;
bitmap[i+1]=temp;
bitmap[i+2]=temp;
bitmap[i+3]=0;
temp=(temp+1);
}
// -- PIXEL DATA -- //
a=19199;
for( i = end_color; i < end_color+19200; i++){bitmap[i] = pixel_1[a]; a=a-1;}
FILE *file;
//use wb+ when writing to binary file .i.e. in binary form whereas w+ for txt file.
file = fopen("AAA.bmp", "wb+");
for( i = 0; i < 20278; i++)
{
fputc(bitmap[i], file);
}
fclose(file);
答案 0 :(得分:0)
如果最终要每个像素16位图像,则图像数据大小为160 * 120 * 2(38400),而不是19200。
当然,您必须调整文件大小。
编辑:由于pixel_1
是16位数据的数组,因此您可以将将其复制到bitmap
的循环更改为:
a = 19199;
for (i = end_color; i < end_color + 19200; i++)
{
*(short *)(bitmap + (i * 2)) = pixel_1[a];
a = a - 1;
}