2014-01-07 30 views
0

我有三個字節存儲三種顏色(紅色,綠色,藍色)的數組,我怎樣才能在c#中的圖片框中顯示這個數組,並且文件的類型是圖像的位圖文件在圖片框中顯示三個字節的數組

byte[,] R=new byte[width, height]; 
byte[,] G=new byte[width, height]; 
byte[,] B=new byte[width, height]; 

這三個數組不是空的,每個數組都有數據存儲。

回答

0

你的意思是:

Bitmap bmp = new Bitmap(width,height); 
for(int i=0;i<width;i++) 
for(int j=0;j<height;j++) { 
    SetPixel(i,j,Color.FromArgb(R[i,j],G[i,j],B[i,j])); 
} 
picturebox.image=bmp; 
0

你必須建立從數據來看,這不會是非常快的,因爲你有交錯的數據單字節數組。基本上,你會做這樣的事情:

var bytes= new byte[width * height * 4]; 

for (var x = 0; x < width; x++) 
    for (var y = 0; y < height; y ++) 
    { 
    bytes[(x + y * width) * 4 + 1] = R[x, y]; 
    bytes[(x + y * width) * 4 + 2] = G[x, y]; 
    bytes[(x + y * width) * 4 + 3] = B[x, y]; 
    } 

然後你可以使用字節數組創建位圖,如下所示:

var bmp = new Bitmap(width, height); 

var data = bmp.LockBits(new Rectangle(0, 0, width, height), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb) 

Marshal.Copy(bytes, 0, data.Scan0, width * height * 4); 

bmp.UnlockBits(data); 

請注意,您應該確保bmp.UnlockBits總是叫,所以你應該把它放在一個finally塊中。

這並不一定是最好或最快的方式,但是這要看你的需求呢:)

如果你真的要在最快的方式,你可能會使用不安全的代碼(不是因爲它的而是因爲.NET位圖是而不是本地管理 - 它是非託管位圖的託管包裝器)。您將爲非託管堆上的字節數組分配內存,然後填充數據並使用以IntPtr scan0作爲參數的構造函數創建位圖。如果正確完成,它應該避免不必要的陣列邊界檢查,以及不必要的複製。