无法强制转换类型为';的对象;System.Data.Linq.Binary';键入';System.

本文关键字:System 对象 Data Linq 键入 Binary 类型 转换 | 更新日期: 2023-09-27 18:00:46

在visual studio中收到错误"无法将类型为System.Data.Linq.Binary的对象强制转换为类型为System.Byte[]"。我将图像存储在sql server数据库中,并以树视图格式显示。我可以打开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;
    }
}

无法强制转换类型为';的对象;System.Data.Linq.Binary';键入';System.

您必须使用Binary中的ToArray方法来获得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;
    }
}

使用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;
    }
}
相关文章: