I have been tackling this problem for some time. I get the image from my DB as a byte[] and i want to convert it to WritableBitmap so i can use binding to show it on my xaml page.
I am using this:
public class ImageConverter : IValueConverter
{
/// <summary>
/// Converts a Jpeg byte array into a WriteableBitmap
/// </summary>
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value is byte[])
{
MemoryStream stream = new MemoryStream((Byte[])value);
WriteableBitmap bmp = new WriteableBitmap(200, 200);
bmp.LoadJpeg(stream);
return bmp;
}
else
return null;
}
/// <summary>
/// Converts a WriteableBitmap into a Jpeg byte array.
/// </summary>
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
The first problem is that it doesn't work. it throws an unspecified exception when it hits bmp.LoadJpeg(stream);
The second problem is regarding the fixed size passed to the WriteableBitmap constructor, how can i know the size of the photo that is coming from the db ? can i make it dynamic somehow ? I guess the second problem is the cause of the first one.
Thanks.
EDIT
I have also tries using PictureDecoder.DecodeJpeg()
like this:
MemoryStream stream = new MemoryStream((Byte[])value);
WriteableBitmap bmp = PictureDecoder.DecodeJpeg(stream);
return bmp;
but it didn't work either. in this case PictureDecoder.DecodeJpeg
suppose to create the bmp object for me. I still get an unspecified error. could it be that i passed the maximum length allowed for the stream ?