2013-08-24 81 views
0

我想將原始RGB24數據數組轉換爲C#中的位圖,但我在這樣做時遇到了麻煩。如何將原始RGB數據數組轉換爲C#中的位圖

這是相應的代碼:

using System.Runtime.InteropServices; 

byte[] frame; 
//... code 
frame = new byte[1280 * 960]; 

// code to get the frame 

System.Runtime.InteropServices.GCHandle pinnedArray = 
     GCHandle.Alloc(frame, GCHandleType.Pinned); 
IntPtr pointer = pinnedArray.AddrOfPinnedObject(); 

Bitmap bmp = new Bitmap(width, height, 3 * width, 
     PixelFormat.Format24bppRgb, pointer); 

MemoryStream JPEGStream = new MemoryStream(); 
bmp.Save(filepath, System.Drawing.Imaging.ImageFormat.Bmp);** 

我得到一個

「型 'System.AccessViolationException' 未處理的異常發生在System.Drawing.dll程序」

與上面的代碼

但是如果我改變:

Bitmap bmp = new Bitmap(width, height, stride, 
     PixelFormat.Format24bppRgb, pointer); 

Bitmap bmp = new Bitmap(width/3, height/3, stride, 
     PixelFormat.Format24bppRgb, pointer); 

我不死機,並獲得3個圖像覆蓋總面積的1/3。我應該得到的是一張覆蓋整個1280 X 960區域空間的單個圖像。

回答

2

Format24bppRgb表示一個像素需要24位(3字節),而不是1,因爲您在樣本中預分配。字節

變化量分配給佔位每像素(以字節爲單位,如果使用不同的大小,不要忘記填充):

frame = new byte[1280 * 960 * 3]; // 24bpp = 3 bytes 
+0

謝謝阿列克謝。我忽略了這一點。現在我的程序沒有崩潰,但是我得到了3張圖像426×320,覆蓋了1280×960像素的1/3,而其餘的2/3是黑色。這是圖像的外觀: http://tinypic.com/r/538ltd/5 我想獲得覆蓋1280 X 960區域空間的塊中的1塊。你有什麼想法? –

0

你試過寬度-1和高度-1?

相關問題