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

 
 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 }

 

posted @ 2018-05-31 13:20  技术_小菜  阅读(4188)  评论(0编辑  收藏  举报