天天看點

如何讀入位圖(四)

用C語言讀取像素資料:

int ReadPixelData(char *filepath,BYTE *imgData)

{

       BITMAPINFOHEADER bmih;

       BITMAPFILEHEADER bmfh;

       BYTE *data;

       FILE *fp;

       int n;

       int width;

       int height;

       int bitCount;

       DWORD dwLineBytes;

       //讀入檔案頭

       n=ReadFileHeader(filepath,&bmfh);

       if(n==-1)

       {

              printf("Can not read the file header of the BMP file.\n");

              return -1;

       }

       //讀入資訊頭

       n=ReadInfoHeader(filepath,&bmih);

              printf("Can not read the info header of the BMP file.\n");

       //獲得資訊頭中有用資料

       width=bmih.biWidth;

       height=bmih.biHeight;

       bitCount=bmih.biBitCount;

       dwLineBytes=GetLineBytes(width,bitCount);

       //檢查配置設定的空間是否正确

       if(_msize(imgData)!=(dwLineBytes*height))

              printf("The size you allocate for the pixel data is not right.\n");

              printf("Fittable size: %ld bytes.\n",(dwLineBytes*height));

              printf("Your size: %ld bytes.\n",sizeof(imgData));

       //建立一個中間的變量

       data=(BYTE*)malloc(dwLineBytes*height*sizeof(BYTE));

       if(!data)

              printf("Can not allocate memory for the pixel data.\n");

       //打開檔案

       fp=fopen(filepath,"rb");

      if(!fp)

              printf("Can not open the file: %s\n",filepath);

              free(data);

       if(bitCount==8)

       {//如果為8位位圖

              fseek(fp,bmfh.bfOffBits,SEEK_SET);//直接跳到像素資料

       else if(bitCount==24)

       {//與上面重複,可以隻寫一處

              fseek(fp,bmfh.bfOffBits,SEEK_SET); //直接跳到像素資料

       else

              printf("Only Support: 8 or 24 bits.\n");

              fclose(fp);

       //讀入像素資料,大小為高度乘上每行所占位元組數

       if(fread(data,dwLineBytes*height*sizeof(BYTE),1,fp)!=1)

              printf("Can not read the pixel data.\n");

       //拷貝讀入的資料給imgData

       memcpy(imgData,data,dwLineBytes*height*sizeof(BYTE));

       //釋放配置設定的中間變量的記憶體

       free(data);

       fclose(fp);//關閉檔案

       return 0;

}

用C語言讀取位圖的像素值:

void PrintPixelData(BYTE *imgData,int width,int height,int bitCount)

       int i;

       int j;

       int p;

       DWORD dwLineBytes=GetLineBytes(width,bitCount);

       {//如果是8位位圖

              for(i=0;i<height;i++)

              {

                     for(j=0;j<width;j++)

                     {

                            //讀取灰階值

                            p=*(imgData+dwLineBytes*(height-1-i)+j);

                            printf("%d,",p);

                     }

                     printf("\n");

              }

       {//如果是24位位圖

                     for(j=0;j<width*3;j++)

                            printf("(");

                            //讀取藍色分量

                            j++;

                            //讀取綠色分量

                            //讀取紅色分量

                            printf("%d) ",p);

              printf("Only supported: 8 or 24 bits.\n");

繼續閱讀