本文介绍了如何使用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;
}

推荐答案

bpp=(int)extract(fp1,24,2); 



如何读取每个像素取决于每个像素的位数。对于最常见的24 bpp的情况,你可以读取3个字节,它将是你的像素的蓝色,绿色和红色值。



看看这里的完整说明: []


这篇关于如何使用C将图像的BMP文件转换为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 01:55