BMP图像四字节对齐的问题

 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

转载于:https://my.oschina.net/u/923087/blog/111212

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值