C 语言

关注公众号 jb51net

关闭
首页 > 软件编程 > C 语言 > 读取BMP图像数据

C语言读取BMP图像数据的源码

投稿:shangke

这篇文章主要介绍了C语言读取BMP图像数据的源码,需要的朋友可以参考下

BMP是英文Bitmap(位图)的简写,它是Windows操作系统中的标准图像文件格式,能够被多种Windows应用程序所支持。随着Windows操作系统的流行与丰富的Windows应用程序的开发,BMP位图格式理所当然地被广泛应用。这种格式的特点是包含的图像信息较丰富,几乎不进行压缩,但由此导致了它与生俱生来的缺点--占用磁盘空间过大。所以,目前BMP在单机上比较流行。

BMP文件格式分析

简介

BMP(Bitmap-File)图形文件是Windows采用的图形文件格式,在Windows环境下运行的所有图象处理软件都支持BMP图象文件格式。Windows系统内部各图像绘制操作都是以BMP为基础的。Windows 3.0以前的BMP图文件格式与显示设备有关,因此把这种BMP图象文件格式称为设备相关位图DDB(device-dependent bitmap)文件格式。Windows 3.0以后的BMP图象文件与显示设备无关,因此把这种BMP图象文件格式称为设备无关位图DIB(device-independent bitmap)格式(注:Windows 3.0以后,在系统中仍然存在DDB位图,象BitBlt()这种函数就是基于DDB位图的,只不过如果你想将图像以BMP格式保存到磁盘文件中时,微软极力推荐你以DIB格式保存),目的是为了让Windows能够在任何类型的显示设备上显示所存储的图象。BMP位图文件默认的文件扩展名是BMP或者bmp(有时它也会以.DIB或.RLE作扩展名)。

位图文件结构表
位图文件 位图文件头 14 字节
位图信息头 40 字节
彩色表(调色板) 4N 字节
位图数据 x 字节

构件详解:

位图文件头
位图文件头包含文件类型、文件大小、存放位置等信息。结构定义如下:

typedef struct tagBITMAPFILEHEADER
  {
        UNIT    bfType;
        DWORD   bfSize;
        UINT    bfReserved1;
        UINT    bfReserved2;
        DWORD   bfOffBits;
  }BITMAPFILEHEADER;

其中:
bfType 说明文件类型,在windows系统中为BM。
bfSize 说明文件大小。
bfReserved1 bfReserved2 保留,设置为0。
bfOffBits 说明实际图形数据的偏移量。

位图信息头

位图信息头包含位图的大小、压缩类型、和颜色格式,结构定义如下:

typedef struct tagBITMAPINFOHEADER
  {
        DWORD   biSize;
        LONG    biWidth;
        LONG    biHeight;
        WORD    biPlanes;
        WORD    biBitCount;
        DWORD   biCompression;
        DWORD   biSizeImage;
        LONG    biXPelsPerMerer;
        LONG    biYPelsPerMerer;
        DWORD   biClrUsed;
        DWORD   biClrImportant;
  }BITMAPINFOHEADER;

其中:
biSize 说明BITMAPINFOHEADER结构所需字节数,在windows系统中为28h
biWidth 说明图像宽度
biHeight 说明图像高度
biPlanes 为目标设备说明位面数,其值设为1
biBitCount每个像素的位数,单色位图为1,256色为8,24bit为24。
biCompression压缩说明,BI_RGB:无压缩,BI_RLE8:8位RLE压缩,BI_RLE4:4位RLE压缩
biSizeImage说明图像大小,如无压缩,可设为0
biXPelsPerMeter水平分辨率
biYPelsPerMeter垂直分辨率
biClrUsed 位图使用的颜色数
biImportant重要颜色数目 

彩色表

彩色表包含的元素与位图所具有的颜色数目相同,像素颜色用结构RGBQUAD来表示:

typedef struct tagRGBQUAD
{
        BYTE    rgbBlue;
        BYTE    rgbGreen;
        BYTE    rgbRed;
        BYTE    rgbReserved;
}RGBQUAD;

其中:
rgbBlue 指定蓝色强度
rgbGreen 指定绿色强度
rgbRed 指定红色强度
rgbReserved保留,设为0

位图数据

紧跟在彩色表后的是图像数据阵列,图像每一扫描行由连续的字节组成,扫描行由底向上存储,阵列中第一字节为左下角像素,最后一字节为右上角像素。

源代码1

/* File name:   bmpTest.c
   Description: Show all Info a bmp file has. including 
   FileHeader Info, InfoHeader Info and Data Part.
   Reference: BMP图像数据的C语言读取源码
*/

#include "stdafx.h"
//#include <stdio.h>
#include <stdlib.h>

#define BITMAPFILEHEADERLENGTH 14   // The bmp FileHeader length is 14
#define BM 19778                    // The ASCII code for BM

/* Test the file is bmp file or not */
void bmpFileTest(FILE* fpbmp);
/* To get the OffSet of header to data part */
void bmpHeaderPartLength(FILE* fpbmp);
/* To get the width and height of the bmp file */
void BmpWidthHeight(FILE* fpbmp);
/* Show bmp file tagBITMAPFILEHEADER info */
void bmpFileHeader(FILE* fpbmp);
/* Show bmp file tagBITMAPINFOHEADER info */
void bmpInfoHeader(FILE* fpbmp);
/* Show the Data Part of bmp file */
void bmpDataPart(FILE* fpbmp);

unsigned int OffSet = 0;    // OffSet from Header part to Data Part
long BmpWidth = 0L;          // The Width of the Data Part
long BmpHeight = 0L;         // The Height of the Data Part

int main(int argc, char* argv[])
{
     /* Open bmp file */
//   FILE *fpbmp = fopen("lena.bmp", "r+");
     FILE *fpbmp = fopen("picture.bmp", "r+");

     if (fpbmp == NULL)
     {
	  fprintf(stderr, "Open lena.bmp failed!!!\n");
	  return 1;
     }

     bmpFileTest(fpbmp);                //Test the file is bmp file or not
     bmpHeaderPartLength(fpbmp);        //Get the length of Header Part
     BmpWidthHeight(fpbmp);             //Get the width and width of the Data Part
     bmpFileHeader(fpbmp);            //Show the FileHeader Information 
     bmpInfoHeader(fpbmp);	        //Show the InfoHeader Information
     bmpDataPart(fpbmp);                //Reserve the data to file 

     fclose(fpbmp);
     return 0;
}

/* Test the file is bmp file or not */
void bmpFileTest(FILE* fpbmp)
{     
     unsigned short bfType = 0;
     fseek(fpbmp, 0L, SEEK_SET);
     fread(&bfType, sizeof(char), 2, fpbmp);
     if (BM != bfType)
     {
	  fprintf(stderr, "This file is not bmp file.!!!\n");
	  exit(1);
     }
}

/* To get the OffSet of header to data part */
void bmpHeaderPartLength(FILE* fpbmp)
{
     fseek(fpbmp, 10L, SEEK_SET);
     fread(&OffSet, sizeof(char), 4, fpbmp);	
     //printf("The Header Part is of length %d.\n", OffSet);
}

/* To get the width and height of the bmp file */
void BmpWidthHeight(FILE* fpbmp)
{
     fseek(fpbmp, 18L, SEEK_SET);
     fread(&BmpWidth, sizeof(char), 4, fpbmp);
     fread(&BmpHeight, sizeof(char), 4, fpbmp);
     //printf("The Width of the bmp file is %ld.\n", BmpWidth);
     //printf("The Height of the bmp file is %ld.\n", BmpHeight);
}

/* Show bmp file tagBITMAPFILEHEADER info */
void bmpFileHeader(FILE* fpbmp)
{
     unsigned short bfType;              //UNIT        bfType;
     unsigned int   bfSize;              //DWORD       bfSize;
     unsigned short bfReserved1;         //UINT        bfReserved1;
     unsigned short bfReserved2;         //UINT        bfReserved2;
     unsigned int   bfOffBits;           //DWORD       bfOffBits;

     fseek(fpbmp, 0L, SEEK_SET);

     fread(&bfType,      sizeof(char), 2, fpbmp);
     fread(&bfSize,      sizeof(char), 4, fpbmp);
     fread(&bfReserved1, sizeof(char), 2, fpbmp);
     fread(&bfReserved2, sizeof(char), 2, fpbmp);
     fread(&bfOffBits,   sizeof(char), 4, fpbmp);

     printf("************************************************\n");
     printf("*************tagBITMAPFILEHEADER info***********\n");
     printf("************************************************\n");
     printf("bfType              is %d.\n", bfType);
     printf("bfSize              is %d.\n", bfSize);
     printf("bfReserved1         is %d.\n", bfReserved1);
     printf("bfReserved2         is %d.\n", bfReserved2);
     printf("bfOffBits           is %d.\n", bfOffBits);
}

/* Show bmp file tagBITMAPINFOHEADER info */
void bmpInfoHeader(FILE* fpbmp)
{
     unsigned int biSize;	          // DWORD        biSize;
     long         biWidth;                // LONG         biWidth;
     long         biHeight;               // LONG         biHeight;
     unsigned int biPlanes;               // WORD         biPlanes;
     unsigned int biBitCount;             // WORD         biBitCount;
     unsigned int biCompression;          // DWORD        biCompression;
     unsigned int biSizeImage;            // DWORD        biSizeImage;
     long         biXPelsPerMerer;        // LONG         biXPelsPerMerer;
     long     	  biYPelsPerMerer;        // LONG         biYPelsPerMerer;
     unsigned int biClrUsed;              // DWORD        biClrUsed;
     unsigned int biClrImportant;         // DWORD        biClrImportant;

     fseek(fpbmp, 14L, SEEK_SET);

     fread(&biSize,          sizeof(char), 4, fpbmp);
     fread(&biWidth,         sizeof(char), 4, fpbmp);
     fread(&biHeight,        sizeof(char), 4, fpbmp);
     fread(&biPlanes,        sizeof(char), 4, fpbmp);
     fread(&biBitCount,      sizeof(char), 4, fpbmp); 
     fread(&biCompression,   sizeof(char), 4, fpbmp);
     fread(&biSizeImage,     sizeof(char), 4, fpbmp);
     fread(&biXPelsPerMerer, sizeof(char), 4, fpbmp);
     fread(&biYPelsPerMerer, sizeof(char), 4, fpbmp);
     fread(&biClrUsed,       sizeof(char), 4, fpbmp);
     fread(&biClrImportant,  sizeof(char), 4, fpbmp);

     printf("************************************************\n");
     printf("*************tagBITMAPINFOHEADER info***********\n");
     printf("************************************************\n");
     printf("biSize              is %d. \n", biSize);
     printf("biWidth             is %ld.\n", biWidth);
     printf("biHeight            is %ld.\n", biHeight);
     printf("biPlanes            is %d. \n", biPlanes);
     printf("biBitCount          is %d. \n", biBitCount);
     printf("biCompression       is %d. \n", biCompression);
     printf("biSizeImage         is %d. \n", biSizeImage);
     printf("biXPelsPerMerer     is %ld.\n", biXPelsPerMerer);
     printf("biYPelsPerMerer     is %ld.\n", biYPelsPerMerer);
     printf("biClrUsed           is %d. \n", biClrUsed);
     printf("biClrImportant      is %d. \n", biClrImportant);
}

/* Show the Data Part of bmp file */
void bmpDataPart(FILE* fpbmp)
{
     int i, j;
//     unsigned char bmpPixel[BmpWidth][BmpHeight];
	 unsigned char bmpPixel[1000][1000];
	 //因为暂时还未找到好的方法,暂且长和宽都设为1000,如果图像的尺寸大于1000,则要重新设置


     unsigned char* bmpPixelTmp = NULL;
     FILE* fpDataBmp;

     /* New a file to save the data matrix */
     if((fpDataBmp=fopen("bmpData.dat","w+")) == NULL)
     {
	  fprintf(stderr, "Failed to construct file bmpData.dat.!!!");
	  exit(1);
     }
     
     fseek(fpbmp, OffSet, SEEK_SET);
     if ((bmpPixelTmp=(unsigned char*)malloc(sizeof(char)*BmpWidth*BmpHeight))==NULL)
     {
	  fprintf(stderr, "Data allocation failed.!!!\n");
	  exit(1);
     }
     fread(bmpPixelTmp, sizeof(char), BmpWidth*BmpHeight, fpbmp);

     /* Read the data to Matrix and save it in file bmpData.dat */
     for(i =0; i < BmpHeight; i++)
     {
	  fprintf(fpDataBmp, "The data in line %-3d:\n", i+1); 
	  for(j = 0; j < BmpWidth; j++)
	  {
	       bmpPixel[i][j] = bmpPixelTmp[BmpWidth*(BmpHeight-1-i)+j];
	       //fwrite(&chartmp, sizeof(char), 1, fpDataBmp);
	       fprintf(fpDataBmp, "%-3d ", bmpPixel[i][j]);
	       if ((j+1)%32 == 0)
	       {
		    fprintf(fpDataBmp, "\n");
	       }
	  }
     }
     /* Used to test the data read is true or false 
	You can open the file using Matlab to compare the data */
     //printf("bmpPixel[2][3]   is %d.\n", bmpPixel[2][3]);
     //printf("bmpPixel[20][30] is %d.\n", bmpPixel[20][30]);

     free(bmpPixelTmp);
     fclose(fpDataBmp);
}

源代码2

// 读取图像2.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
//#include <stdio.h>
#include <stdlib.h>


#define BITMAPFILEHEADERLENGTH 14   // The bmp FileHeader length is 14
#define BM 19778                    // The ASCII code for BM


/* Test the file is bmp file or not */
void bmpFileTest(FILE* fpbmp);
/* To get the OffSet of header to data part */
void bmpHeaderPartLength(FILE* fpbmp);
/* To get the width and height of the bmp file */
void BmpWidthHeight(FILE* fpbmp);
//get r,g,b data
void bmpDataPart(FILE* fpbmp);
// output data to corresponding txt file
void bmpoutput(FILE *fpout);

unsigned int OffSet = 0;    // OffSet from Header part to Data Part
long width ;          // The Width of the Data Part
long height ;         // The Height of the Data Part
unsigned char r[2000][2000],output_r[2000][2000];
unsigned char g[2000][2000],output_g[2000][2000];
unsigned char b[2000][2000],output_b[2000][2000];


int main(int argc, char* argv[])
{
     /* Open bmp file */
	unsigned char *fp_temp;


    FILE *fpbmp;
    FILE *fpout;


    fpbmp= fopen("lena.bmp", "rb");


    if (fpbmp == NULL)
    {
		printf("Open bmp failed!!!\n");
		return 1;
    }


    fpout= fopen("out.bmp", "wb+");
    if (fpout == NULL)
    {
		printf("Open out.bmp failed!!!\n");
		return 1;
    }
     
		bmpFileTest(fpbmp);                //Test the file is bmp file or not
		bmpHeaderPartLength(fpbmp);        //Get the length of Header Part
    BmpWidthHeight(fpbmp);             //Get the width and width of the Data Part
     
     
	//
	fseek(fpbmp, 0L, SEEK_SET);
	fseek(fpout, 0L, SEEK_SET);
	 
	fp_temp=(unsigned char *)malloc(OffSet);
	fread(fp_temp, 1, OffSet, fpbmp);
	fwrite(fp_temp,1,OffSet,fpout);
		 
	bmpDataPart(fpbmp);                //Reserve the data to file 
     

	/*
	 
	 
	 如果您想对图片进行处理,请您再这里插入处理函数!!!!!!!!!!!!!!!!!!
	 
	*/
	bmpoutput(fpout);
	fclose(fpbmp);
	fclose(fpout);
    return 0;
}


void bmpoutput(FILE* fpout)
{
	int i, j=0;
	int stride;
	unsigned char* pixout=NULL;
	   
	stride=(24*width+31)/8;
	stride=stride/4*4;
	pixout=(unsigned char *)malloc(stride);
	 
	fseek(fpout, OffSet, SEEK_SET);
	for(j=0;j<height;j++)
	{
	   for(i=0;i<width;i++)
			{
				pixout[i*3+2]=output_r[height-1-j][i];
				pixout[i*3+1]=output_g[height-1-j][i];
				pixout[i*3]  =output_b[height-1-j][i];
			}
		fwrite(pixout, 1, stride, fpout);

	}
}


void bmpDataPart(FILE* fpbmp)
{
    int i, j=0;
	int stride;
	unsigned char* pix=NULL;

	FILE* fpr;
	FILE* fpg;
	FILE* fpb;
     
    if((fpr=fopen("bmpr.txt","w+")) == NULL)
    {
		printf("Failed to construct file bmpr.txt.!!!");
		exit(1);
    }
    if((fpg=fopen("bmpg.txt","w+")) == NULL)
    {
		printf("Failed to construct file bmpg.txt.!!!");
		exit(1);
    }
	if((fpb=fopen("bmpb.txt","w+")) == NULL)
    {
	printf("Failed to construct file bmpb.txt.!!!");
	exit(1);
    }
 
    fseek(fpbmp, OffSet, SEEK_SET);
	stride=(24*width+31)/8;
	stride=stride/4*4;
	pix=(unsigned char *)malloc(stride);
 
	for(j=0;j<height;j++)
	{
		fread(pix, 1, stride, fpbmp);

		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];


			output_r[height-1-j][i] = pix[i*3+2];
			output_g[height-1-j][i] = pix[i*3+1];
			output_b[height-1-j][i] = pix[i*3];
		}
	}

	for(i =0; i < height; i++)
    {
		for(j = 0; j < width-1; j++)
		{   
			fprintf(fpb,"%4d",b[i][j]);
			fprintf(fpg,"%4d",g[i][j]);
			fprintf(fpr,"%4d",r[i][j]);
		}
		fprintf(fpb,"%4d\n",b[i][j]);
		fprintf(fpg,"%4d\n",g[i][j]);
		fprintf(fpr,"%4d\n",r[i][j]);
	}
  
	fclose(fpr);
	fclose(fpg);
	fclose(fpb); 
}


void bmpFileTest(FILE* fpbmp)
{     
     unsigned short bfType = 0;
 
     fseek(fpbmp, 0L, SEEK_SET);//seek_set 起始位置
     fread(&bfType, sizeof(char), 2, fpbmp);
     if (BM != bfType)
     {
		 printf("This file is not bmp file.!!!\n");
		 exit(1);
     }
}


/* To get the OffSet of header to data part */
void bmpHeaderPartLength(FILE* fpbmp)
{
    fseek(fpbmp, 10L, SEEK_SET);
    fread(&OffSet, sizeof(char), 4, fpbmp);  
    printf("The Header Part is of length %d.\n", OffSet);
}


/* To get the width and height of the bmp file */
void BmpWidthHeight(FILE* fpbmp)
{
    fseek(fpbmp, 18L, SEEK_SET);
    fread(&width, sizeof(char), 4, fpbmp);
    fseek(fpbmp, 22L, SEEK_SET);
    fread(&height, sizeof(char), 4, fpbmp);
    printf("The Width of the bmp file is %ld.\n", width);
    printf("The Height of the bmp file is %ld.\n", height);
}

到此这篇关于C语言读取BMP图像数据的源码的文章就介绍到这了,更多相关读取BMP图像数据内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文