C#将RGB图像格式数据转换为BITMAP和BITSOURCE对象


1 public void RGBTOBITMAP(BYTE/*自定义的数据IntPtr*/ bits,int width/*图像的宽度*/,int height/*图像的高度*/) 2 int widthStep = width*3; //一般默认步长为宽度的3倍 3 int lenData = widthStep * height;//数据长度,24位图像数据的长度=宽度*高度*3 4 int len = 0; //代表长度 5 //bits图像帧数据 6 byte[] buffer = new byte[len];//创建指定长度byte数据 7 Marshal.Copy(bits, buffer, 0, buffer.Length); 8 9 10 /*****下面的就是将RGB数据转换为BITMAP对象******/ 11 int stride = width * 3; 12 GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned); 13 int scan0 = (int)handle.AddrOfPinnedObject(); 14 scan0 += (height - 1) * stride; 15 System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(width, height, -stride, System.Drawing.Imaging.PixelFormat.Format24bppRgb, (IntPtr)scan0); 16 handle.Free(); 17 /********************************************/ 18 19 /*****下面的代码是显示到wpf的Image控件上实时显示******/ 20 IntPtr ip = bitmap.GetHbitmap();//从GDI+ Bitmap创建GDI位图对象 21 22 BitmapSource bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(ip, IntPtr.Zero, Int32Rect.Empty, 23 System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions()); 24 25 image1.Source = bitmapSource; 26 /********************************************/ 27 bitmap.Dispose(); //bitmap释放 28 29 /*使用DeleteObejct这个函数需要从gdi32.dll导入函数 30 [System.Runtime.InteropServices.DllImport("gdi32.dll")] 31 public static extern bool DeleteObject(IntPtr hObject);*/ 32 DeleteObject(ip);

猜你喜欢

转载自www.cnblogs.com/cyymfm1314/p/9116193.html