Skip to content

Instantly share code, notes, and snippets.

@posaunehm
Created February 4, 2013 23:31
Show Gist options
  • Save posaunehm/4710725 to your computer and use it in GitHub Desktop.
Save posaunehm/4710725 to your computer and use it in GitHub Desktop.
A value converter between bitmap and bitmapsource Inspired by http://www.codeproject.com/Articles/104929/Bitmap-to-BitmapSource and Matt's comment in the article.
public class WinFormBitmapConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var bitmap = value as Bitmap;
if (bitmap == null)
{
return null;
}
try
{
using (var memoryStream = new MemoryStream())
{
// You need to specify the image format to fill the stream.
// I'm assuming it is PNG
bitmap.Save(memoryStream, ImageFormat.Png);
memoryStream.Seek(0, SeekOrigin.Begin);
return CreateBitmapSourceFromBitmap(memoryStream);
}
}
catch (Exception)
{
return null;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
private static BitmapSource CreateBitmapSourceFromBitmap(Stream stream)
{
var bitmapDecoder = BitmapDecoder.Create(
stream,
BitmapCreateOptions.PreservePixelFormat,
BitmapCacheOption.OnLoad);
// This will disconnect the stream from the image completely...
var writable = new WriteableBitmap(bitmapDecoder.Frames.Single());
writable.Freeze();
return writable;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment