我一直致力于用 c 创建我自己的 BMP 阅读器,并且我设法读取了 Header 和 HeaderInfo,但是当我将图像数据读取到我的结构数组时,我得到了错误的输出。 预期输出是 10,我得到的是 20。 这是我的代码:
#include<stdio.h>
typedef struct
{
unsigned char Red;
unsigned char Green;
unsigned char Blue;
} pixel;
#pragma pack(2) /*2 byte packing */
typedef struct
{
unsigned short int type;
unsigned int size;
unsigned short int reserved1,reserved2;
unsigned int offset;
}header;
typedef struct
{
unsigned int size;
int width,height;
unsigned short int bits;
unsigned int compression;
unsigned int pixelsize;
int xresolution,yresolution;
unsigned int ncolors;
unsigned int importantcolors;
}headerInfo;
void main()
{
header head;
headerInfo headInfo;
int counter=0;
FILE *leftpixel;
leftpixel = fopen("left.bmp","rb+");
if(leftpixel==NULL)
{
printf("Error opening first file");
}
fread(&head,1,sizeof(head),leftpixel);
printf("%x ",head.type);
printf("%u ",head.size);
printf("%u ",head.offset);
printf("\n");
fread(&headInfo,1,sizeof(headInfo),leftpixel);
printf("%d ",headInfo.width);
printf("%d ",headInfo.height);
printf("\n");
fseek(leftpixel,54,SEEK_SET);
pixel im[480][640];
int i,j;
for (i = 0; i < 480; i++) {
for (j = 0; j < 640; j++) {
fread(&im[i][j], sizeof(unsigned char),headInfo.pixelsize, leftpixel);
if(im[i][j].Red>(im[i][j].Green+im[i][j].Blue))
{
counter++;
}
}
}
printf("counter =%d ", counter);
printf("\n");
}
最佳答案
您永远不应该使用硬编码常量,如fseek(leftpixel,54,SEEK_SET)
;从 header 的 bfOffBits 字段中提取像素图的偏移量,在其他情况下,使用文件 header 中的信息而不是您的猜测。另请阅读@V-X 在该问题下的评论。
关于c - 在c中读取bmp图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26650047/