2010-01-04 60 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);