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

发布于 2024-11-26 16:36:43 字数 2003 浏览 1 评论 0原文

我想在 XAML 中绑定以 varbinary 类型保存在数据库中的图像。我该怎么做?

例如northwind数据库中的图片字段。

谢谢

编辑 1:)

我编写此代码用于转换图像字段(Northwind 数据库中类别表中的图片字段),但每次我得到 Exception:

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.");
    }
}

And :

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.

I want to bind an image that save in varbinary type in database in XAML.How I can do that?

for example Picture field in northwind DataBase.

thanks

EDIT 1:)

I write this codes for convert Image field (Picture field in Categories table in Northwind DataBase) but every time I get Exception:

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.");
    }
}

And :

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.");
    }
}

and the exception:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

方觉久 2024-12-03 16:36:44

如果您从数据库获取字节数组,则无需将其转换为图像或位图图像......
您可以将图像的 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;
        }
    }
}

希望这会对您有所帮助...

If you are getting byte array from database then no need to convert that to image or bitmap image...
You can bind Source property of image to byte array.. wpf internally handle the byte array and it converts byte array to image...

Edit:

If you still want to convert byte array to Bitmap image here is the method which was tested

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;
        }

I have crated a sample using above method...

Xaml code:

<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>

Code Behind

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;
        }
    }
}

Hope this will help you...

无悔心 2024-12-03 16:36:44

这只能使用自定义转换器来实现。有关如何实现“图像”部分的详细信息,请参阅 此处了解有关创建转换器的详细信息。

This can be achieved only using a custom converter. Look at this for details on how to implement the "image" part and here for details about creating a converter.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文