c语言读取BMP图片的RGB数据

BMP图片是位图(bitmap),一般未压缩,要读取BMP文件只要知道它的文件结构就可以了,具体格式可以百度或者google,就不多说了,几个重要的点在代码里面有注释。

/**
	c语言读取位图信息 
**/

#includestdio.h
#includemalloc.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;
	else
		return 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;jheight;j++)
	{
	   fread(pix, 1, stride, fp);
	   for(i=0;iwidth;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;
}


最新回复(0)
/jishubKeqizvRWm1dU_2BT0TlVFw_2Fd8XA3r41t8FytyjA_3D_3D4794613
8 简首页