您的位置:首页 > 其它

BMP图像四字节对齐的问题

2013-03-01 00:00 260 查看
1、内存分配单位是32位的,即4字节;
2、位图中每行象素的数据是连续的,而下一行不能和上一行共一个分配单元(4字节),所以每行象素的数据长度必须是4字节的倍数;
3、代码说明如下:

int WidthBytes( int nBits, int nWidth )
{//nBits为色彩位数, nWidth为每行象素个数
int nWidthBytes;//每行象素的数据长度

nWidthBytes = nWidth;
if( nBits == 1 ) nWidthBytes = ( nWidth + 7 ) / 8;
else if( nBits == 4 ) nWidthBytes = ( nWidth + 1 ) / 2; /*竟然没有8位的。256色不是很常见吗?!*/
else if( nBits == 16 ) nWidthBytes = nWidth * 2;
else if( nBits == 24 ) nWidthBytes = nWidth * 3;//24位真彩色
else if( nBits == 32 ) nWidthBytes = nWidth * 4;//32位真彩色

//*******四字节对齐*******
while( ( nWidthBytes & 3 ) != 0 ) nWidthBytes++;
//*******四字节对齐*******
return( nWidthBytes );

}

--------------------------------------------------------------------------------------------------------------------------

我的理解:

1.bmp为4字节的方式,因此在buf中,不论存取还是显示,都是以4字节为单位的。

2.接下来的问题就是怎么确定一行到底要怎么对齐。

首先,int 的除法。结果还是int,会舍掉小数点。所以。我们加上3字节。再除以4。就可以防止字节数变少

eg:Width=1(位图的宽度为1像素) BitCount=24(24位的像素位数。1个像素24位即3字节)

Width*BitCount/8=3得出占用的字节数是3.

(3+3)/4 这是求出“基数”,为1. 如果没有加上3的话,商为0,明显不符合题意。

1*4得出LineBytes=4.

同理,如果是以位为单位,就是加上31. Width*BitCount+31

then: (Width*BitCount+31)/32 *4
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: