在c中读取bmp图像

时间:2014-10-30 10:02:25

标签: c image-processing bmp

我一直在用c创建自己的BMP阅读器,我设法读取Header和HeaderInfo,但是当我将图像数据读取到我的struct数组时,输出错误。 预期的产量是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");

}  

1 个答案:

答案 0 :(得分:1)

你永远不应该使用fseek(leftpixel,54,SEEK_SET)中的硬编码常量;从头文件的bfOffBits字段中提取偏移到pixmap,在其他情况下使用文件头中的信息而不是您的猜测。另请阅读@ V-X在该问题下的评论。