锁定在C#位图的矩形时锁定指针
-
21-08-2019 - |
题
这可以是以下未回答的问题的重复:
Help with bitmap lock - Format8bppIndexed
我以下面的方式锁定的图像:
// PixelFormat is 8BppIndexed in my case.
Bitmap bmp = new Bitmap("mySampleImage.tif");
// ClipRectangle will be a Rectangle such as {x=128, y=290, width=250, height=200},
// selected by the user by seeing the image on screen. Thus, it's a valid region
BitmapData data = bmp.LockBits(rect, ImageLockMode.ReadOnly, bmp.PixelFormat);
unsafe
{
byte* origin = (byte*)data.Scan0.ToPointer();
// Processing...
}
在该处理部分,我步在Y方向上在ClipRectangle的像素。然而,像素应该是与存储器访问错误的有效的回报,说我不能解除引用的指针。
例如,在一个704x600的图像使用:
ClipRectangle = {x=128, y=290, width=250, height=200}
像素(128x321)
应该是有效的。通过在数学手动键入以获得在中间窗口该像素时,得到如下所示:
origin + (321 * stride) + 128 0x053a80c0 *(origin + (321 * stride) + 128): Cannot dereference 'origin + (321 * stride) + 128'. The pointer is not valid.
步幅是704,在我的软件逻辑上来与精确指针位置作为中间窗口,所以一切似乎是正确的。从290-320在Y像素可提领就好了。如果我不是锁定整个位图,我所有的逻辑进行罚款,但我对我是否得到正确的像素,或者锁定矩形是如何在LockBits使用的疑虑。
我为什么不能访问锁定预期中的像素的BitmapData时,我只锁定我需要的区域?
解决方案
在锁使用具有矩形比特偏移量,BitmapData.Scan0
不返回位图来源的,而是指定的矩形原点。
所以,如果你使用的:
Rectangle rect = new Rectangle(128, 290, 250, 200);
BitmapData data = bmp.LockBits(rect, ImageLockMode.ReadOnly, bmp.PixelFormat);
则最大从Scan0
偏移(250 * Stride) + 200
。
在换句话说,在(128x321)的像素将处于(Scan0 + (321 - 290) * Stride)
。
不隶属于 StackOverflow