zoukankan      html  css  js  c++  java
  • [WPF 学习] 16.WPF Bitmap to ImageSource的几种方式

    Image是显示图片的控件,若要显示一张Bitmap的图片,必须转换成ImageSouce,并赋值给Souce,有如下几种方式:

    A:

            private ImageSource ToBitmapSourceA(Bitmap bitmap)
            {
                MemoryStream stream = new MemoryStream();
                bitmap.Save(stream, ImageFormat.Bmp);
                stream.Position = 0;
                BitmapImage bitmapImage = new BitmapImage();
                bitmapImage.BeginInit();
                bitmapImage.StreamSource = stream;
                bitmapImage.EndInit();
                return bitmapImage;
            }
    

    B:

            [DllImport("gdi32")]
            private static extern int DeleteObject(IntPtr o);
            public ImageSource ToBitmapSourceB(Bitmap bitmap)
            {
                IntPtr ptr = bitmap.GetHbitmap(); //obtain the Hbitmap
                BitmapSource bitmapSource = Imaging.CreateBitmapSourceFromHBitmap(ptr, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
                DeleteObject(ptr); //release the HBitmap
                return bitmapSource;
            }
    
    

    C:

            public ImageSource ToBitmapSourceC(Bitmap bitmap)
            {
               
                var bmpData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                BitmapSource bitmapSource = BitmapSource.Create(bitmap.Width, bitmap.Height, 96, 96, PixelFormats.Bgr24, myPalette, bmpData.Scan0, bitmap.Width * bitmap.Height * 3, bitmap.Width * 3);
                bitmap.UnlockBits(bmpData);
                return bitmapSource;
            }
    
    

    在我的电脑上测试:运行A需要5.2毫秒,B需2.6毫秒,C需1.2毫秒,显然C是最快的。

    更何况如果用opencv获取摄像头数据的话,还不需要转换成Bitmap格式,直接用Mat.DataPointer就搞定了。

            private ImageSource ToImageSourceD(Mat frame)
            {
                return BitmapSource.Create(frame.Width, frame.Height, 96, 96, PixelFormats.Bgr24, myPalette, frame.DataPointer, frame.Width * frame.Height * 3, frame.Width * 3);
            }
    
    

    是不是方便多了?

    是不是方便多了?是不是方便多了?是不是方便多了?是不是方便多了?是不是方便多了?是不是方便多了?是不是方便多了?是不是方便多了?是不是方便多了?是不是方便多了?是不是方便多了?是不是方便多了?是不是方便多了?是不是方便多了?是不是方便多了?是不是方便多了?是不是方便多了?是不是方便多了?是不是方便多了?是不是方便多了?是不是方便多了?是不是方便多了?是不是方便多了?是不是方便多了?

  • 相关阅读:
    jQuery Event.delegateTarget 属性详解
    velocity 判断 变量 是否不是空或empty
    触碰jQuery:AJAX异步详解
    jQuery Select操作大集合
    常用元素默认margin和padding值问题探讨
    九大排序算法再总结
    八大排序算法
    JavaScript中toStirng()与Object.prototype.toString.call()方法浅谈
    使用CSS3的appearance属性改变元素的外观
    CSS清浮动处理(Clear与BFC)
  • 原文地址:https://www.cnblogs.com/catzhou/p/14357646.html
Copyright © 2011-2022 走看看