1

收到错误“无法将“System.Data.Linq.Binary”类型的对象转换为“System.Byte []”类型。在视觉工作室。我将图像存储在我以树视图格式显示的 sql server db 中。我可以打开 dbml 设计器并将所有 System.Data.Linq.Binary 更改为 System.Byte,但图像模糊不清。有什么想法吗?

这是代码:

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;
    }
}
4

2 回答 2

2

您将不得不使用ToArrayfrom 方法Binary来获取byte[]值。

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;
    }
}
于 2013-02-24T23:46:44.327 回答
1

采用System.Data.Linq.Binary.ToArray()

由于字节的转换,不太可能导致模糊和模糊,而是由于您用来显示它的控件未与像素网格对齐,或者稍微调整大小,拉伸图像并导致图像放大和模糊. 确保图像未拉伸并且控件与像素网格对齐SnapsToDevicePixels="True"

此外,这里是您的代码的一些帮助:

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;
    }
}
于 2013-02-24T23:37:19.813 回答