无法将'System.Data.Linq.Binary'类型的对象强制转换为'System.Byte []'

时间:2013-02-24 23:31:15

标签: c# wpf visual-studio-2010

收到错误'无法转换类型&System; 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;
    }
}

2 个答案:

答案 0 :(得分:2)

您必须使用ToArray中的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;
    }
}

答案 1 :(得分: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;
    }
}