The way we do it is to store the images as blobs in the database (they're fairly small images, 4-500k, so storing them in the db shouldn't cause any perf problems), retreive them as byte arrays, and then use a ValueConverter
to convert from byte[]
to BitMap
.
The XAML for the image control looks like this:
<Image Source="{Binding Path=RawImageData,
Converter={StaticResource ByteArrayToBitmapImageConverter},
Mode=OneWay}" />
The property we bind to in the ViewModel is simply a byte[]
like this;
private byte[] _rawImageData;
public byte[] RawImageData
{
get { return _rawImageData; }
set
{
if (value != _rawImageData)
{
_rawImageData = value;
NotifyPropertyChanged("RawImageData");
}
}
}
And then the ValueConverte
looks like this;
public class ByteArrayToBitmapImageConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var rawImageData = value as byte[];
if (rawImageData == null)
return null;
var bitmapImage = new System.Windows.Media.Imaging.BitmapImage();
using (var stream = new MemoryStream(rawImageData))
{
bitmapImage.BeginInit();
bitmapImage.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
bitmapImage.CacheOption = BitmapCacheOption.Default;
bitmapImage.StreamSource = stream;
bitmapImage.EndInit();
}
return bitmapImage;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}