【WPF】WriteableBitmap和BitmapImage的相互转换
public BitmapImage ConvertWriteableBitmapToBitmapImage(WriteableBitmap wbm) { BitmapImage bmImage = new BitmapImage(); using (MemoryStream stream = new MemoryStream()) { PngBitmapEncoder encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(wbm)); encoder.Save(stream); bmImage.BeginInit(); bmImage.CacheOption = BitmapCacheOption.OnLoad; bmImage.StreamSource = stream; bmImage.EndInit(); bmImage.Freeze(); } return bmImage; }
public static class ImageHelpers { public static BitmapImage ToBitmapImage(this WriteableBitmap wbm) { BitmapImage bmImage = new BitmapImage(); using (MemoryStream stream = new MemoryStream()) { PngBitmapEncoder encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(wbm)); encoder.Save(stream); bmImage.BeginInit(); bmImage.CacheOption = BitmapCacheOption.OnLoad; bmImage.StreamSource = stream; bmImage.EndInit(); bmImage.Freeze(); } return bmImage; } }
以上一个普通方法,第二个则是扩展方法。