如何使用C将图像的BMP文件转换为数组

编程入门 行业动态 更新时间:2024-10-23 01:48:34
本文介绍了如何使用C将图像的BMP文件转换为数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想编写一个程序,使用C中的宏将图像的位图文件转换为二进制形式 我尝试过:

I want to write a program to convert a bitmap file of an image into binary form using macros in C What I have tried:

#include<stdio.h> #include<conio.h> #include<stdlib.h> #include<math.h> #define RGB(r,g,b) (r|g<<8|b<<16) long extract(FILE *,long ,int ); void information(FILE *); long extract(FILE *fp1,long offset,int size) { unsigned char *ptr; unsigned char temp='0'; long value=0L; int i; //to initialize the ptr ptr=&temp; //sets the file pointer at specific position i.e. after the offset fseek(fp1,offset,SEEK_SET); //now extracting (size) values starting from the offset for(i=1;i<=size;i++) { fread(ptr,sizeof(char),1,fp1); value=(long)(value+(*ptr)*(pow(256,(i-1)))); //combining the values one after another in a single variable } return value; } void information(FILE *fp1) { printf("\nThe width of the bitmap in pixel : %d pixel\n",(int)extract(fp1,18L,4)); printf("\nThe height of the bitmap in pixel : %d pixel\n",(int)extract(fp1,22L,4)); } int main() { int row,col; int i,j,k; int dataoffset,offset; char num[2]; int color; FILE *fp1,*fp2; if((fp1=fopen("C:\\Users\\Raghava\\Desktop\\logo104.bmp","rb"))==NULL) { printf("\a\nCant open the image.\nSystem is exiting."); } //setting the file pointer at the beginning rewind(fp1); //CHECKING WHETHER THE FILE IS IN BMP FORMAT OR NOT, WE CHECK THE NUMBER OF THE FILE, NUMBER'S OFFSET IS 0 i.e. IT'S STORED AT THE FRONT OF THE IMAGE, AND THE SIZE IS 2 //at first extracting the number for(i=0;i<2;i++) { num[i]=(char)extract(fp1,i,1); } //now checking if((num[0]=='B') && (num[1]=='M')); else { printf("\a The image is not a bitmap image.\n System is exiting ...... "); } //storing the header information information(fp1); //get the starting position or offset of the data(pixel) dataoffset=(int)extract(fp1,10,4); row=(int)extract(fp1,22,4); //printf("%d\n",row); //get the number of columns col=(int)extract(fp1,18,4); //printf("%d\n",col); //storing the data if((fp2=fopen("pixel2.txt","wb"))==NULL) { printf("\a\n Error while creating a file.\n System is exiting...."); //exit(0); } offset=dataoffset; for(k=0;k<row;k++) { for(j=0;j<col;j++) { /*if(RGB(0,0,0)) { fprintf(fp2,"1"); } else { fprintf(fp2,"0"); }*/ } fprintf(fp2,"\r\n"); } printf("\n For pixels see pixel2.txt."); return 0; }

推荐答案

您需要读取每像素的位数: You'll need to read the number of bits per pixel: bpp=(int)extract(fp1,24,2);

如何读取每个像素取决于每个像素的位数。对于最常见的24 bpp的情况,你可以读取3个字节,它将是你的像素的蓝色,绿色和红色值。 看看这里的完整说明: BMP文件格式 - 维基百科 [ ^ ]

更多推荐

如何使用C将图像的BMP文件转换为数组

本文发布于:2023-10-04 09:25:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1467147.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   转换为   如何使用   图像   文件

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!