注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.
"尝试读取或写入受保护的内存。这是通常指示其他内存已损坏。
我遇到此错误在我的代码的Marshal.Copy部分。我相信我的数据不是损坏也不受保护。
我想知道在什么情况下这不会发生。我有列表 <> 的位图。这仅发生在我处理的第一个索引 [0]。
因此,这里是怎么做到:-第一,我用[此代码获取位图的像素数据]此代码:
Bitmap tmp_bitmap = BitmapFromFile[0]; Rectangle rect = new Rectangle(0, 0, tmp_bitmap.Width, tmp_bitmap.Height); System.Drawing.Imaging.BitmapData bmpData = tmp_bitmap.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb); int length = bmpData.Stride * bmpData.Height; byte[] bytes = new byte[length]; // Copy bitmap to byte[] Marshal.Copy(bmpData.Scan0, bytes, 0, length); tmp_bitmap.UnlockBits(bmpData);
它工作正常,没有错误发生。
然后,我将应用此代码[此操作将删除像素数据线扫描填充]:
byte[] bytes = new byte[bmpData.Width * bmpData.Height * 3]; for (int y = 0; y < bmpData.Height; ++y) { IntPtr mem = (IntPtr)((long)bmpData.Scan0 + y * bmpData.Stride * 3); Marshal.Copy(mem, bytes, y * bmpData.Width * 3, bmpData.Width * 3); //This is where the exception is pointed. }
每当我要处理的第一个图像 — — 第二,最后,没有问题在所有,它给我这一错误。
我希望你能帮我用这个。谢谢你在前进。
解决方法 1:
你似乎会考虑 3 倍的每一行 ; 步幅您的代码将仅工作第一次第三次的图像 ;之后,你确实有超出允许的范围。基本上:
bmpData.Scan0 + y * bmpData.Stride * 3
看起来真的很不可靠。"跨越"使用的字节数 (包括填充) 通过每个行。只是通常情况下,就是:
bmpData.Scan0 + y * bmpData.Stride