BMP图像,每像素位数的问题

问题描述 投票:-2回答:1

我正在使用生成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);
c bmp
1个回答
0
投票

如果最终需要每像素16位图像,则图像数据大小为160 * 120 * 2(38400),而不是19200。

你必须调整de文件大小。

编辑:因为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;
}
© www.soinside.com 2019 - 2024. All rights reserved.