C# 使用Marshal.Copy()将位图设置为int[]
我使用C# 使用Marshal.Copy()将位图设置为int[],c#,bitmap,marshalling,C#,Bitmap,Marshalling,我使用Marshal.Copy()将像素信息从Bitmap复制到int[]数组,问题在于到达该数组的信息完全错误,如: [0] = -8682109; [1] = -8682109; [2] = -8616573; [3] = -8616573; [4] = -8550527; and so on... 该方法的代码为:
Marshal.Copy()
将像素信息从Bitmap
复制到int[]
数组,问题在于到达该数组的信息完全错误,如:
[0] = -8682109;
[1] = -8682109;
[2] = -8616573;
[3] = -8616573;
[4] = -8550527;
and so on...
该方法的代码为:
private unsafe int[] BmpToBytes_Unsafe(Bitmap bmp)
{
BitmapData bData = bmp.LockBits(new Rectangle(new Point(), bmp.Size),
ImageLockMode.ReadOnly,
PixelFormat.Format32bppRgb);
// number of bytes in the bitmap
byteCount = bData.Stride * (bmp.Height);
int[] bytes = new int[byteCount / 4];
Marshal.Copy(bData.Scan0, bytes, 0, byteCount/4);
// don't forget to unlock the bitmap!!
bmp.UnlockBits(bData);
return bytes;
当我使用一个
字节[]
数组时,存储的信息是正确的,所以我不知道这里发生了什么。IMHO,你的字节数是一个字节数,现在你将字节除以4,并期望得到一组整数,实际上是字节。演员阵容的执行不是您想要的
要将字节数组转换为int数组,请使用:
System.BitConverter.ToInt32(mybyteArray,4) 这些值完全正常。它们是32bpp像素,alpha通道为0xff(通常的值)。换句话说:-8682109==0xff7b8583。任何alpha值>=128都将使该值为负值,因为它设置了符号位
使用uint[]而不是int[]可以使其更易于查看。问题是方法Marshal.Copy不接受uint[],您知道如何操作该值,分离RGB组件吗?使用Color.FromArgb(),它接受int。