【WPF】Bitmap和BitmapImage的相互转换

2016-12-16 18:58:33来源:CSDN作者:qq_18995513人点击

搜索资料的正确姿势:

  • 谷歌上搜关键字 C# WPF Convert Bitmap BitmapImage

StackOverflow上有很多解决方案,这里选择了试过可行的方法:

public class SystemUtils{    /// <summary>    /// Bitmap --> BitmapImage    /// </summary>    /// <param></param>    /// <returns>BitmapImage</returns>    public static BitmapImage BitmapToBitmapImage(Bitmap bitmap)    {        using (MemoryStream stream = new MemoryStream())        {            bitmap.Save(stream, ImageFormat.Bmp);            stream.Position = 0;            BitmapImage result = new BitmapImage();            result.BeginInit();            // According to MSDN, "The default OnDemand cache option retains access to the stream until the image is needed."            // Force the bitmap to load right now so we can dispose the stream.            result.CacheOption = BitmapCacheOption.OnLoad;            result.StreamSource = stream;            result.EndInit();            result.Freeze();            return result;        }    }    /// <summary>    /// BitmapImage --> Bitmap    /// </summary>    /// <param></param>    /// <returns></returns>    public static Bitmap BitmapImageToBitmap(BitmapImage bitmapImage)    {        // BitmapImage bitmapImage = new BitmapImage(new Uri("../Images/test.png", UriKind.Relative));        using (MemoryStream outStream = new MemoryStream())        {            BitmapEncoder enc = new BmpBitmapEncoder();            enc.Frames.Add(BitmapFrame.Create(bitmapImage));            enc.Save(outStream);            Bitmap bitmap = new Bitmap(outStream);            return new Bitmap(bitmap);        }    }}

最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台