簡體   English   中英

無法將'System.Data.Linq.Binary'類型的對象強制轉換為'System.Byte []'

[英]Unable to cast object of type 'System.Data.Linq.Binary' to type 'System.Byte[]'

收到錯誤'無法將類型'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;
    }
}

您必須使用BinaryToArray方法來獲取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;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM