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

本文关键字:图像 类型 VarBinary 数据库 存在 控件 绑定 保存 | 更新日期: 2023-09-27 18:03:54

我想绑定一个图像,保存在varbinary类型的数据库在XAML。我怎么能做到呢?

以北风数据库中的图片字段为例。

感谢

编辑1:)

我写这个代码转换图像字段(图片字段在类别表在北风数据库),但每次我得到异常:

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.

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

如果你从数据库中获得字节数组,那么不需要将其转换为图像或位图图像…您可以将图像的源属性绑定到字节数组..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;
        }
    }
}

这只能使用自定义转换器来实现。有关如何实现"image"部分的详细信息,请参阅此处,以及有关创建转换器的详细信息。