C# 封送处理.Copy()时发生异常
为了更快地访问,我想使用字节数组读取位图的像素。因此,我使用了这里提供的代码: 这是我的密码:C# 封送处理.Copy()时发生异常,c#,marshalling,C#,Marshalling,为了更快地访问,我想使用字节数组读取位图的像素。因此,我使用了这里提供的代码: 这是我的密码: private static int GetBitmapDataInByteArray(out byte[] bArr, ref System.Drawing.Bitmap bmp) { int Length = -1; System.Drawing.Imaging.BitmapData bmpData = bmp.LockBits( new System.Drawi
private static int GetBitmapDataInByteArray(out byte[] bArr, ref System.Drawing.Bitmap bmp)
{
int Length = -1;
System.Drawing.Imaging.BitmapData bmpData = bmp.LockBits(
new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height),
System.Drawing.Imaging.ImageLockMode.ReadWrite, bmp.PixelFormat);
Length = System.Math.Abs(bmpData.Stride) * bmpData.Height;
bArr = new byte[Length];
/* Exception on this line: */
System.Runtime.InteropServices.Marshal.Copy(bmpData.Scan0, bArr, 0, Length);
bmp.UnlockBits(bmpData);
return Length;
}
我得到一个System.AccessViolationException-在受保护的内存中读取或写入
有人知道为什么吗?菲利普·帕雷是对的。手动指定像素格式可以解决此问题。可能是32/64位之间的冲突?该
bmp
参数不需要是ref
,因为您没有分配给它(这里不是您的问题,只是一个注释)在手动指定像素格式的我的机器上运行良好。我会使用PixelFormat.Format32bppArgb