BMP图像的文件格式

wincf 2003-10-20 10:51:59
昨天研究了一下BMP文件,现将过程和结果写下:

(一)方法: 1.用PhotoShop创建两个BMP文件"1.bmp"(1*3), "2.bmp"(2*3)
2.比较"1.bmp"与"2.bmp"即可知道文件头的大概样子,对文件"2.bmp",
其像素内容如下:
0xf3f3f3 0x00ff00 0x0000ff
0x112233 0x445566 0x778899
在观察文件内容,即可知道像素排列方法.

(二)结果:

<Head>:
42 4D 50 00 00 00 00 00 00 00 36 00 00 00 28 00
00 00 x0 x1 x2 x3 y0 y1 y2 y3 01 00 18 00 00 00
00 00 00 00 00 00 12 0B 00 00 12 0B 00 00 00 00
00 00 00 00 00 00

说明:
x0 x1 x2 x3 为文件宽度[象素数],其中低位在左高位在右
例如: 258 表示成 02 01 00 00
y0 y1 y2 y3 为文件高度[象素数],高低位表示同上
(其中 42 4D 50 后面几个字节对不同的文件有不同内容,
我没发现其意义,但将起改为0,图像同样可以正确显示)

<Body>:
每三位表示一个象素[RGB],其格式为 xx yy zz
其中xx是Blue值, yy是Green值, zz是Red值,普通
的RGB()函数直接保存进去是不对的,应该进行转换

另外,其像素的存储是从左下角开始,自左往右,自下往上
存储,例如以下的像素排列:
1 2 3 4
5 6 7 8
在BMP文件中,像素存储的顺序为 5,6,7,8,1,2,3,4

<Tail>:
BMP的文件尾如下:
00 00 00 00 00

(三).对此编了一个函数,得到图形设备指针(CDC*)后,
即可将指定区域保存为(*.BMP)

int saveBmp(int width, int height, CString filePath)
{
CString tail = filePath.Right(3);
tail.MakeLower();
if ( tail != "bmp" || width<=0 || height<=0 )
return 0;
CFile fHandle;
fHandle.Open( filePath, CFile::modeCreate | CFile::modeWrite, NULL );
unsigned char bmpHead1[18] = { 0x42,0x4D,0x50,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x36,0x00,0x00,0x00,0x28,0x00,0x00,0x00 };
fHandle.Write( bmpHead1, 18 );
unsigned char bmpSize[8];
sizeToBinary( width, height, bmpSize );
fHandle.Write( bmpSize, 8 );
unsigned char bmpHead2[28] = { 0x01,0x00,0x18,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x12,0x0B,0x00,0x00,0x12,0x0B,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00 };
fHandle.Write( bmpHead2, 28 );

long buf[1];
for ( int y=height; y>=0; y-- )
{
for ( int x=0; x<width; x++ )
{
COLORREF color = pDC->GetPixel(x,y);
buf[0] = ( (0xff0000&color)>>16) | (0x00ff00&color) | ((0x0000ff&color)<<16);
fHandle.Write( buf, 3 );
}
}
unsigned char bmpTail[5] = { 0x00,0x00,0x00,0x00,0x00 };
fHandle.Write( bmpTail, 5 );
fHandle.Close();
return 1;
}


void sizeToBinary(int width, int height, unsigned char buf[])
{
if ( width<=255 )
{
buf[0] = width;
buf[1] = 0x00;
}
else
{//High bit is in the end
buf[0] = width-256 ;
buf[1] = width/256 ;
}
buf[2] = 0x00;
buf[3] = 0x00;
if ( height<=255 )
{
buf[4] = height;
buf[5] = 0x00;
}
else
{
buf[4] = height-256 ;
buf[5] = height/256 ;
}
buf[6] = 0x00;
buf[7] = 0x00;
}
...全文
46 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
wqs6 2003-10-20
  • 打赏
  • 举报
回复
呵呵!
有专研精神!

19,468

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC 图形处理/算法
社区管理员
  • 图形处理/算法社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧