Reputation: 1798
Receiving the error 'Unable to cast object of type 'System.Data.Linq.Binary' to type 'System.Byte[]'.' In visual studio. I am have images stored in a sql server db that I am displaying in a treeview format. I can open the dbml designer and change all the System.Data.Linq.Binary to System.Byte but the images come out fuzzy and blurry. Any thoughts?
Here is the code:
public class ImageBytesConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
BitmapImage bitmap = new BitmapImage();
if (value != null)
{
byte[] photo = (byte[])value;
MemoryStream stream = new MemoryStream();
int offset = 78;
stream.Write(photo, offset, photo.Length - offset);
bitmap.BeginInit();
bitmap.StreamSource = stream;
bitmap.EndInit();
}
return bitmap;
}
}
Upvotes: 1
Views: 6807
Reputation: 27419
Use System.Data.Linq.Binary.ToArray()
The fuzziness and blurriness very unlikely due to the conversion of the bytes, but rather to the control you are using to display it not being aligned to the pixel grid, or else being resized slightly, stretching the image and causing it to be upscaled and blurred. Make sure the image is not stretched and the control is aligned to the pixel grid with SnapsToDevicePixels="True"
Also, here is some help for your code:
public class ImageBytesConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
BitmapImage bitmap = new BitmapImage();
bitmap.CacheOption = BitmapCacheOption.OnLoad;
if (value != null)
{
byte[] photo = ((System.Data.Linq.Binary)value).ToArray();
using(MemoryStream stream = new MemoryStream())
{
int offset = 78;
stream.Write(photo, offset, photo.Length - offset);
bitmap.BeginInit();
bitmap.StreamSource = stream;
bitmap.EndInit();
}
return bitmap;
}
return null;
}
}
Upvotes: 1
Reputation: 43596
You will have to use the ToArray
method from Binary
to get the byte[]
value.
public class BinaryToByteArrayConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value != null && value is System.Data.Linq.Binary)
{
byte[] array = (value as System.Data.Linq.Binary).ToArray();
BitmapImage bitmap = new BitmapImage();
using (MemoryStream stream = new MemoryStream())
{
int offset = 78;
stream.Write(array, offset, array.Length - offset);
bitmap.BeginInit();
bitmap.StreamSource = stream;
bitmap.EndInit();
}
return bitmap;
}
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return null;
}
}
Upvotes: 2