直接位图访问 [英] Direct Bitmap Access

查看:60
本文介绍了直接位图访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了ProccessImage函数,但是当我将其与大小为1680 * 1050的图像一起使用时,结果是错误(访问内存)
我不明白为什么?


I wrote the ProccessImage function,but when I use it with an image of size 1680*1050 ,the result is an error(memory access)
I don''t understand why?


HBITMAP ProccessImage(HBITMAP hBitmap )
{
	BITMAP Bmp;
	GetObject(hBitmap,sizeof(Bmp),&Bmp);
	LPDWORD pixels = (LPDWORD)Bmp.bmBits;
		for(int row = 0; row < Bmp.bmHeight; ++row)
			for(int col = 0; col < Bmp.bmWidth; ++col)
				pixels[row * Bmp.bmWidthBytes / 4 + col] = RGB(0,127,255) ;
		return hBitmap;
}

推荐答案

我没有发现您的示例有任何问题,只是您假定这是一个4字节像素的位图.如果像素类型较小,则会解释访问冲突.对bmBitsPixel进行测试可以使您确定这是原因.
好的,现在我们知道您每个像素有3个字节,我们需要稍微重新排列循环.首先,我们必须将指向当前像素的指针定义为字节指针,而不是DWORD指针.然后,我们跨扫描行以3字节为增量:

I don''t see anything wrong with your example, except that you assume that this is a bitmap of 4-byte pixels. If the pixel type is smaller that would explain the access violation. A test of bmBitsPixel would give you certainty that this is the cause.

Edited: Ok, now that we know that you have 3 bytes per pixel we need to rearrange your loop a little. First of all, we have to define the pointer to the current pixel as a byte pointer instead of DWORD pointer. Then we step in 3-byte increments across a scan line:

for(int row = 0; row < Bmp.bmHeight; ++row)
{
    BYTE* p = ((BYTE*) Bmp.bmBits) + row * Bmp.bmWidthBytes;
    for(int col = 0; col < Bmp.bmWidth; ++col)
    {
        *p++ = 255; // blue
        *p++ = 127; // green
        *p++ = 0;   // red
    }
}



如您所见,通过这种方式,我们还可以避免为每个像素计算像素的地址.请注意,有必要重新计算每一行的像素指针,因为在每一行的末尾可能会出现几个松弛字节,以填充到下一个偶数边界.这就是为什么BITMAP结构保留成员bmWidthBytes来告诉我们确切的行数的原因.



As you see, in this way we can also avoid to calculate the pixel''s address for every single pixel. Note that it is necessary to recalculate the pixel pointer for every row, because at the end of each row there might occur several slack bytes to fill up to the next even boundary. That is why the BITMAP structure holds the member bmWidthBytes to tell us exactly how long a row is.


这篇关于直接位图访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆