【原創】C語言讀取BMP格式圖片



【原創】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);
}




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM