2010-01-04 112 views
5

我使用Marshal.Copy()Bitmap中的像素信息复制到int[]数组,问题在于事实上即将传递到此数组的信息全部来自错,如:使用Marshal.Copy()将位图转换为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; 

当我使用的是byte[]阵列,这是存储是正确的信息,所以我不知道发生了什么这里。

回答

5

这些值是完全正常的。它们是32bpp像素,Alpha通道处于0xff(通常的值)。换句话说:-8682109 == 0xff7b8583。任何alpha值> = 128会使值为负,因为它设置了符号位。

使用uint []而不是int []可以更容易看清。

+0

问题是,方法Marshal.Copy不采取uint [],你知道我怎么操纵这个值,分开RGB组件? – 2010-01-05 16:27:08

+0

使用Color.FromArgb(),它需要一个int。 – 2010-01-05 16:37:05

0

恕我直言,你的bytecount是一个字节的数量,现在你正在将字节除以4,并期待一组整数,这实际上是字节。演员表不会按照你的要求演出。

要转换字节数组int数组使用:

System.BitConverter.ToInt32(mybyteArray,4);