2010-06-20 25 views
2

我想從包含顏色數據的數組中編程創建一個位圖。使用下面的代碼,當顯示在一個picturebox中時,我會並排顯示3個重複的失真圖像。有人能告訴我哪裏出問題了嗎?如何以編程方式從顏色數組創建24bpp位圖?

public Bitmap CreateBM(int[,] imgdat) 
    { 
     Bitmap bitm = new Bitmap(imgdat.GetUpperBound(1) + 1, imgdat.GetUpperBound(0) + 1, PixelFormat.Format24bppRgb); 
     BitmapData bitmapdat = bitm.LockBits(new Rectangle(0, 0, bitm.Width, bitm.Height), ImageLockMode.ReadWrite, bitm.PixelFormat); 
     int stride = bitmapdat.Stride; 

     byte[] bytes = new byte[stride * bitm.Height]; 
     for (int r = 0; r < bitm.Height; r++) 
     { 
      for (int c = 0; c < bitm.Width; c++) 
      { 
       Color color = Color.FromArgb(imgdat[r, c]); 
       bytes[(r * bitm.Width) + c * 3] = color.B; 
       bytes[(r * bitm.Width) + c * 3 + 1] = color.G; 
       bytes[(r * bitm.Width) + c * 3 + 2] = color.R; 
      } 
     } 


     System.IntPtr scan0 = bitmapdat.Scan0; 
     Marshal.Copy(bytes, 0, scan0, stride * bitm.Height); 
     bitm.UnlockBits(bitmapdat); 

     return bitm; 
    } 
} 

回答

5

你想通過stridebitm.Width每一行增加索引,而不是隻。

bytes[(r * stride) + c * 3] = color.B; 
bytes[(r * stride) + c * 3 + 1] = color.G; 
bytes[(r * stride) + c * 3 + 2] = color.R; 
+0

謝謝!那樣做了。 – 2010-06-20 16:23:12