C#中的访问冲突异常
本文关键字:异常 访问冲突 | 更新日期: 2023-09-27 18:27:28
我正在C#中进行图像处理项目。我使用OTSU阈值方法。我收到以下异常"试图读取或写入受保护的内存。这通常表明其他内存已损坏。"我在谷歌上搜索堆栈溢出超过2天,但没有得到正确的解决方案。我只收到少数图像的此错误,其他图像运行良好。。。
public void Convert2GrayScaleFast(Bitmap bmp)
{
BitmapData bmData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height),
ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
unsafe
{
byte* p = (byte*)(void*)bmData.Scan0.ToPointer();
int stopAddress = (int)p + bmData.Stride * bmData.Height;
while ((int)p != stopAddress)
{
p[0] = (byte)(.299 * p[2] + .587 * p[1] + .114 * p[0]);
p[1] = p[0];
p[2] = p[0];
p += 3;
}
}
bmp.UnlockBits(bmData);
}
我得到了这行中的异常
p[0] = (byte)(.299 * p[2] + .587 * p[1] + .114 * p[0]);
不要使用"工具"菜单->"选项"->"调试"->"常规"->取消选中此选项"在模块加载时抑制JIT优化"来绕过异常。我尝试了所有的方法,但都不起作用。
这是抛出异常的图片。非常感谢你帮我解决这个问题。
将条件更改为:
while ((int)p < stopAddress)
您还应该考虑步幅四舍五入到四字节边界,并且可以是负数(位图是自下而上的)https://msdn.microsoft.com/en-us/library/system.drawing.imaging.bitmapdata.stride(v=vs.110).aspx我建议:
int numberOfBytesPerPixel = Image.GetPixelFormatSize(bmp.PixelFormat) / 8;
int stopAddress = (int)p + (bmData.Width * numberOfBytesPerPixel) * bmData.Height;
while ((int)p < stopAddress)
{
// add pixel manipulation here
p += numberOfBytesPerPixel;
}