I have a converter in some legacy code, that is doing something that seems wrong, but I don't know bitmaps very well. It looks like it's based on https://stackoverflow.com/a/3427114/57883 with some added capabilities.
using System;
using System.Collections.Generic;
using System.Drawing.Imaging;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Data;
using System.Windows.Media.Imaging;
namespace CompanyName.Converters
{
[ValueConversion(typeof(System.Drawing.Image), typeof(System.Windows.Media.ImageSource))]
/// <summary>
/// One-way converter from System.Drawing.Image to System.Windows.Media.ImageSource
/// </summary>
public class ImageConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
// empty images are empty...
if (value == null)
{
return null;
}
if (value.GetType() == typeof(System.Drawing.Image))
{
var image = (System.Drawing.Image)value;
// Winforms Image we want to get the WPF Image from...
var bitmap = new System.Windows.Media.Imaging.BitmapImage();
bitmap.BeginInit();
MemoryStream memoryStream = new MemoryStream();
// Save to a memory stream...
image.Save(memoryStream, ImageFormat.Bmp);
// Rewind the stream...
memoryStream.Seek(0, System.IO.SeekOrigin.Begin);
bitmap.StreamSource = memoryStream;
bitmap.EndInit();
bitmap.Freeze();
return bitmap;
}
else if (value.GetType() == typeof(System.Drawing.Bitmap))
{
var image = value as System.Drawing.Bitmap;
System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(image);
using (MemoryStream memory = new MemoryStream())
{
bitmap.Save(memory, ImageFormat.Png);
memory.Position = 0;
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.StreamSource = memory;
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.EndInit();
bitmapImage.Freeze();
return bitmapImage;
}
}
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return null;
}
}
}
Why in the world would you System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(image);
? isn't this just creating a copy of the bitmap in memory without any benefit? Is this just horrible code or is there a legitimate reason to copy the bitmap before converting it?