1 public void RGBTOBITMAP(BYTE/*自定義的數據IntPtr*/ bits,int width/*圖像的寬度*/,int height/*圖像的高度*/) 2 { 3 int widthStep = width*3; //一般默認步長為寬度的3倍 4 int lenData = widthStep * height;//數據長度,24位圖像數據的長度=寬度*高度*3 5 int len = 0; //代表長度 6 //bits圖像幀數據 7 byte[] buffer = new byte[len];//創建指定長度byte數據 8 Marshal.Copy(bits, buffer, 0, buffer.Length); 9 10 11 /*****下面的就是將RGB數據轉換為BITMAP對象******/ 12 int stride = width * 3; 13 GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned); 14 int scan0 = (int)handle.AddrOfPinnedObject(); 15 scan0 += (height - 1) * stride; 16 System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(width, height, -stride, System.Drawing.Imaging.PixelFormat.Format24bppRgb, (IntPtr)scan0); 17 handle.Free(); 18 /********************************************/ 19 20 /*****下面的代碼是顯示到wpf的Image控件上實時顯示******/ 21 IntPtr ip = bitmap.GetHbitmap();//從GDI+ Bitmap創建GDI位圖對象 22 23 BitmapSource bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(ip, IntPtr.Zero, Int32Rect.Empty, 24 System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions()); 25 26 image1.Source = bitmapSource;//image1表示wpf的image控件變量 27 /********************************************/ 28 bitmap.Dispose(); //bitmap釋放 29 30 /*使用DeleteObejct這個函數需要從gdi32.dll導入函數 31 [System.Runtime.InteropServices.DllImport("gdi32.dll")] 32 public static extern bool DeleteObject(IntPtr hObject);*/ 33 DeleteObject(ip); 34 }
