c語言讀取BMP圖片的RGB資料

來源:互聯網
上載者:User

BMP圖片是位元影像(bitmap),一般未壓縮,要讀取BMP檔案只要指導它的檔案結構就可以了,具體格式可以百度或者google,就不多說了,幾個重要的點在代碼裡面有注釋。

/**c語言讀取位元影像資訊 **/#include<stdio.h>#include<malloc.h>#define BM 19778// 位元影像的標誌#define PATH "d:\\test.bmp"  //開啟的檔案路徑 //判斷是否是位元影像,在0-1位元組 int IsBitMap(FILE *fp){unsigned short s;fread(&s,1,2,fp);if(s==BM)return 1;elsereturn 0;} //獲得圖片的寬度,在18-21位元組 long getWidth(FILE *fp){long width;fseek(fp,18,SEEK_SET);fread(&width,1,4,fp);return width;}//獲得圖片的高度 ,在22-25位元組 long getHeight(FILE *fp){long height;fseek(fp,22,SEEK_SET);fread(&height,1,4,fp);return height;}  //獲得每個像素的位元,在28-29位元組 unsigned short getBit(FILE *fp){unsigned short bit;fseek(fp,28,SEEK_SET);fread(&bit,1,2,fp);return bit;} //獲得資料的起始位置unsigned int getOffSet(FILE *fp){unsigned int OffSet;fseek(fp,10L,SEEK_SET);fread(&OffSet,1,4,fp);return OffSet;}//獲得映像的資料void getData(FILE* fp,unsigned char *r,unsigned char *g,unsigned char *b){    FILE* fpr;FILE* fpg;FILE* fpb;int i, j=0;int stride;unsigned char* pix=NULL;long height,width;height=getHeight(fp);width=getWidth(fp);fseek(fp, getOffSet(fp), SEEK_SET);//找到位元影像的資料區 stride=(24*width+31)/8;//對齊,計算一個width有多少個8位 stride=stride/4*4;//取四的倍數 r,g,b,alph //寫入數組 pix=(unsigned char *)malloc(stride);for(j=0;j<height;j++){   fread(pix, 1, stride, fp);   for(i=0;i<width;i++){*(r+(height-1-j)+i)=pix[i*3+2];*(g+(height-1-j)+i)=pix[i*3+1];*(b+(height-1-j)+i)=pix[i*3];}}//寫入檔案 fpr=fopen("d:\\bmpr.txt","w+");fpg=fopen("d:\\bmpg.txt","w+");fpb=fopen("d:\\bmpb.txt","w+");for(i =0; i < height; i++)     {for(j = 0; j < width-1; j++){   fprintf(fpr,"%4d",*(r+i+j));fprintf(fpg,"%4d",*(g+i+j));fprintf(fpb,"%4d",*(b+i+j));}fprintf(fpr,"%4d",*(r+i+j));fprintf(fpg,"%4d",*(g+i+j));fprintf(fpb,"%4d",*(b+i+j)); }  fclose(fpr);fclose(fpg);fclose(fpb); } int main(){long width,height;FILE *fp=fopen(PATH,"r");unsigned char *r,*g,*b;int i,j;r=(unsigned char *)malloc(4000);b=(unsigned char *)malloc(4000);g=(unsigned char *)malloc(4000);if(IsBitMap(fp))printf("該檔案是位元影像!\n");else{printf("該檔案不是位元影像!\n");fclose(fp);return 0; } printf("width=%ld\nheight=%ld\n",getWidth(fp),getHeight(fp));printf("該映像是%d位元影像\n",getBit(fp));printf("OffSet=%d\n",getOffSet(fp));getData(fp,r,g,b);return 1;}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.