如何将Image控件绑定到以VarBinary类型保存在数据库中的Image

时间:2011-07-27 09:36:00

标签: c# wpf data-binding c#-4.0

我想在XAML中绑定一个以varbinary类型保存在数据库中的图像。我能做到吗?

例如Northwind DataBase中的图片字段。

感谢

编辑1:)

我为转换图像字段编写此代码(Northwind DataBase中的Categories表中的图片字段),但每次出现异常时:

class ImageConverter : IValueConverter
{
    object IValueConverter.Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value == null) { return null; }

        var image = (System.Drawing.Image)value;
        var bitmap = new System.Windows.Media.Imaging.BitmapImage();
        bitmap.BeginInit();
        MemoryStream memoryStream = new MemoryStream();
        image.Save(memoryStream, ImageFormat.Bmp);
        memoryStream.Seek(0, System.IO.SeekOrigin.Begin);
        bitmap.StreamSource = memoryStream;
        bitmap.EndInit();
        return bitmap;

    }

    object IValueConverter.ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new Exception("The method or operation is not implemented.");
    }
}

并且:

class ImageConverter : IValueConverter
{
    object IValueConverter.Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value != null && value is byte[])
        {
            byte[] bytes = value as byte[];
            MemoryStream stream = new MemoryStream(bytes);
            BitmapImage image = new BitmapImage();
            image.BeginInit();
            image.StreamSource = stream;
            image.EndInit();
            return image;
        }
        return null;
    }

    object IValueConverter.ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new Exception("The method or operation is not implemented.");
    }
}

和例外:

Provide value on 'System.Windows.Markup.StaticResourceHolder' threw an exception.

2 个答案:

答案 0 :(得分:4)

如果从数据库获取字节数组,则无需将其转换为图像或位图图像... 您可以将图像的Source属性绑定到字节数组.wpf在内部处理字节数组,它将字节数组转换为图像...

修改

如果您仍想将字节数组转换为位图图像,则此方法是经过测试的方法

public BitmapImage ImageFromBytearray(byte[] imageData)
        {

            if (imageData == null)
                return null;
            MemoryStream strm = new MemoryStream();
            strm.Write(imageData, 0, imageData.Length);
            strm.Position = 0;
            System.Drawing.Image img = System.Drawing.Image.FromStream(strm);

            BitmapImage bitmapImage = new BitmapImage();
            bitmapImage.BeginInit();
            MemoryStream memoryStream = new MemoryStream();
            img.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Bmp);
            memoryStream.Seek(0, SeekOrigin.Begin);
            bitmapImage.StreamSource = memoryStream;
            bitmapImage.EndInit();

            return bitmapImage;
        }

我使用上述方法创建了一个样本...

Xaml代码:

<Window x:Class="WpfApplication1.ImageFromByteArray"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="ImageFromByteArray" Height="300" Width="300" Name="Root">
    <Grid>
        <Image Source="{Binding ImageSource,ElementName=Root}" Height="300" Width="300"  RenderOptions.BitmapScalingMode="HighQuality"/>
    </Grid>
</Window>

代码背后

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.IO;

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for ImageFromByteArray.xaml
    /// </summary>
    public partial class ImageFromByteArray : Window
    {


        public byte[] ByteArray
        {
            get
            {
                return (byte[])GetValue(ByteArrayProperty);
            }
            set
            {
                SetValue(ByteArrayProperty, value);
            }
        }

        // Using a DependencyProperty as the backing store for ByteArray.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty ByteArrayProperty =
            DependencyProperty.Register("ByteArray", typeof(byte[]), typeof(ImageFromByteArray));



        public BitmapImage ImageSource
        {
            get { return (BitmapImage)GetValue(ImageSourceProperty); }
            set { SetValue(ImageSourceProperty, value); }
        }

        // Using a DependencyProperty as the backing store for ImageSource.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty ImageSourceProperty =
            DependencyProperty.Register("ImageSource", typeof(BitmapImage), typeof(ImageFromByteArray), new UIPropertyMetadata(null));


        public ImageFromByteArray()
        {
            InitializeComponent();
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            if (dlg.ShowDialog().GetValueOrDefault())
            {
                FileStream fs = new FileStream(dlg.FileName, FileMode.Open, FileAccess.Read);
                ByteArray = new byte[fs.Length];
                fs.Read(ByteArray, 0, System.Convert.ToInt32(fs.Length));
                fs.Close();
                ImageSource = ImageFromBytearray(ByteArray);
            }
        }


        public BitmapImage ImageFromBytearray(byte[] imageData)
        {

            if (imageData == null)
                return null;
            MemoryStream strm = new MemoryStream();
            strm.Write(imageData, 0, imageData.Length);
            strm.Position = 0;
            System.Drawing.Image img = System.Drawing.Image.FromStream(strm);

            BitmapImage bitmapImage = new BitmapImage();
            bitmapImage.BeginInit();
            MemoryStream memoryStream = new MemoryStream();
            img.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Bmp);
            memoryStream.Seek(0, SeekOrigin.Begin);
            bitmapImage.StreamSource = memoryStream;
            bitmapImage.EndInit();

            return bitmapImage;
        }
    }
}

希望这会对你有帮助......

答案 1 :(得分:0)

这只能使用自定义转换器来实现。有关如何实现“图像”部分的详细信息,请查看this,有关创建转换器的详细信息,请查看here