您的位置:首页 > 其它

BITMAP文件格式及读写

2009-11-30 20:49 555 查看
这是自己编写的Bitmap的一个格式及其读写的文件,主要需要注意以下几点:

1) 图像在内存中存放时有字节对齐。在32位机中,已4字节对齐,即图像的每一行的实际所占的空间应该是4字节的倍数。因此

访问时必须首先获取图像实际的宽度,GetPitch实现这一功能。

2) 使用#pragma pack(push,1),#pragma pack(pop)对就是为了强制取消结构体的字节对齐。这样确保Bitmap文件的Header

部分为54字节。
3) 使用inline函数是为了提高访问效率,但是也会带来代码变长的弊端。

#ifndef BITMAP_H
#define BITMAP_H
#include <stdio.h>
#include <fcntl.h>
#include <io.h>
typedef unsigned long LONG;
typedef unsigned short WORD;
typedef unsigned char BYTE;
typedef unsigned long DWORD;

#pragma pack(push,1) //one byte aligned
typedef struct
{
WORD bfType; //bm
DWORD bfSize; //the size of bitmap file
WORD bfReserved1;
WORD bfReserved2;
DWORD bfOffBits; //the data section offset the file header
} BMPFILEHEADER_T;
#pragma pack(pop)

typedef struct
{
DWORD biSize; //the size of bitmap info header section
LONG biWidth; //the height of the bitmap
LONG biHeight; //the width of the bitmap
WORD biPlanes; //the number of bit planes ,always set 1
WORD biBitCount; //the bits of one pixel
DWORD biCompression;
DWORD biSizeImage; //the size of image data
LONG biXPelsPerMeter; //device parameter
LONG biYPelsPerMeter;
DWORD biClrUsed;
DWORD biClrImportant;
} BMPINFOHEADER_T;

class Bitmap
{
public:

Bitmap(){pData=NULL;}
Bitmap(int _width,int _height)
{
int pitch;
pitch=GetPitch(_width);

//File Header Section
bFH.bfType = 0x4d42; //bm
bFH.bfSize = pitch*_height+sizeof(BMPFILEHEADER_T)+sizeof(BMPINFOHEADER_T);// total file size
bFH.bfReserved1 = 0; // reserved
bFH.bfReserved2 = 0; // reserved
bFH.bfOffBits = bFH.bfSize - pitch*_height;

//Info Header Section
bIH.biSize=sizeof(BMPINFOHEADER_T);
bIH.biWidth=_width;
bIH.biHeight=_height;
bIH.biPlanes=1;
bIH.biBitCount=24;
bIH.biCompression=0;
bIH.biSizeImage=pitch*_height;
bIH.biXPelsPerMeter=0;

//Data Section
pData=new BYTE[pitch*_height]; //bytes aligned(4)
}
BYTE *GetData(){return pData;}
int GetPitch()
{
return (((bIH.biBitCount>>3)*bIH.biWidth+3)>>2)<<2;
}
int GetPitch(int width)
{
return ((3*width+3)>>2)<<2;
}
inline int Width(){return bIH.biWidth;}
inline int Height(){return bIH.biHeight;}
void SaveBitmap(char *filename)
{
int p_out;
p_out=open(filename,O_CREAT|O_WRONLY|O_BINARY|O_TRUNC);
write(p_out,&bFH,sizeof(BMPFILEHEADER_T));
write(p_out,&bIH,sizeof(BMPINFOHEADER_T));
write(p_out,pData,bIH.biSizeImage);
close(p_out);

}
void LoadBitmap(char *filename)
{
int p_in;
p_in=open(filename,O_RDONLY|O_BINARY);
read(p_in,&bFH,sizeof(BMPFILEHEADER_T));
read(p_in,&bIH,sizeof(BMPINFOHEADER_T));
if(pData)
{
delete[]pData;
}
pData=new BYTE[bIH.biSizeImage];
read(p_in,pData,bIH.biSizeImage);
close(p_in);

}

~Bitmap()
{
delete[]pData;
}
private:
BMPFILEHEADER_T bFH;
BMPINFOHEADER_T bIH;
BYTE *pData;

};
#endif
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: