Bitmap转换到BitmapSource

Bitmap转换到BitmapSource

简单记录一些方法,由于项目用的wpf写的但是相机采图回调是获取的Bitmap所以必须要进行转换才能使用,但是一般的转换方式或出现内存的问题所以这里分享一种我人为比较好的方式。

/// 
    /// 转换Bitmap到BitmapSource
    /// 
    /// 
    /// 
    public static System.Windows.Media.Imaging.BitmapSource GetBitmapSource(System.Drawing.Bitmap bmp)
    {
        System.Windows.Media.Imaging.BitmapFrame bf = null;

        using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
        {
            bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
            bf = System.Windows.Media.Imaging.BitmapFrame.Create(ms, System.Windows.Media.Imaging.BitmapCreateOptions.None, System.Windows.Media.Imaging.BitmapCacheOption.OnLoad);

        }
        return bf;
        //return System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(bmp.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
    }

你可能感兴趣的:(C#,WPF控件)