如何从SQL Server数据库检索图像到WPF窗体? (LINQ,数据绑定,SQL) [英] How to retrieve images from SQL Server database into WPF form?? (LINQ, Databinding, SQL)

查看:98
本文介绍了如何从SQL Server数据库检索图像到WPF窗体? (LINQ,数据绑定,SQL)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个便宜的窗口,我将数据插入数据库。我的数据库列如下:

  col name(varchar),
col age(int),
col photo(image)(all NOT NULL)

现在我想从db进入我的窗口我有一个列表框,我检索这样的名称(LINQ查询)

  public void updateListbox(){
DataClasses1DataContext dc = new DataClasses1DataContext();
var query = from d in dc.tablename select s;

_listBox1.ItemsSource = query.ToList();
}

我的xaml绑定代码如下所示:

 < ListBox ... DisplayMemberPath =Name/> 

所以这些名称现在正在列表框中显示。



我的下一步是显示窗口/窗体上列表框中选择的代表人物的图像/照片。我在这样的文本框中使用age属性:

 < TextBlock ... Text ={Binding ElementName = _listBox1,Path = SelectedItem.Age}/> 

但我不知道如何将图像检索到我的wpf窗口。



我保存这样的图像

  byte [] image = File.ReadAllBytes(@imagepath ); 
...
sqlcommandobject.Parameters.Add(new SqlParameter(@ Photo,image));
...

通过使用openFileDialog加载图像(-path),然后再进入数据库。只是检索是我的问题。我真的希望像现在这样简单的绑定,但我想没有办法通过这样做来检索图像:

 < Image ... Source ={Binding ElementName = _listBox,Path = SelectedItem.Photo}/> 

由于二进制数据必须转换回图像对象(?),而我失去了如何做到这一点,并与绑定结合。任何人都有想法?



感谢您阅读!

解决方案

您可以创建一个转换器将值从 byte [] 转换为 BitmapSource

  [ValueConversion(typeof(byte []),typeof(BitmapSource))] 
public class ByteArrayToImageConverter:IValueConverter
{
public object Convert ,类型targetType,对象参数,CultureInfo文化)
{
byte [] bytes =(byte [])value;
使用(MemoryStream ms = new MemoryStream(bytes))
{
BitmapImage image = new BitmapImage();
image.BeginInit();
image.StreamSource = ms;
image.EndInit();
返回图像;
}
}

public object ConvertBack(object value,Type targetType,object parameter,CultureInfo culture)
{
BitmapSource image =(BitmapSource)value ;
BitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(image));
使用(MemoryStream ms = new MemoryStream())
{
encoder.Save(ms);
return ms.ToArray();
}
}
}

($ code> ConvertBack 方法编码为PNG,您可能需要根据需要进行更改,或者您可能不需要 ConvertBack


I have a cheapo window where I insert data into a database. My db-columns are the following:

col name(varchar),  
col age (int),  
col photo (image) (all NOT NULL)

Now I want to retrieve the info from the db into my window. I have a listbox where I retrieve the names like this (LINQ query)

public void updateListbox(){
DataClasses1DataContext dc = new DataClasses1DataContext();
var query = from s in dc.tablename select s;

_listBox1.ItemsSource = query.ToList();
}

My xaml code for binding looks like this:

<ListBox ... DisplayMemberPath="Name"/>

so the names are now being displayed in the listbox.

My next step is to display the image/photo of the representative person that is selected in the listbox on my window/form. I did it with the age property in a textblock like this:

<TextBlock ... Text="{Binding ElementName=_listBox1, Path=SelectedItem.Age}" />

but I have no idea how to retrieve the image into my wpf window.

I save the image like this

byte[] image = File.ReadAllBytes(@imagepath);
...
sqlcommandobject.Parameters.Add(new SqlParameter("@Photo", image));
...

by using openFileDialog to load the image(-path) before insterting into the db. Just retrieving is my problem now. I really would like to keep the binding as simple as it is at this moment, but I guess there is no way to retrieve the image by doing something like this:

<Image ... Source="{Binding ElementName=_listBox, Path=SelectedItem.Photo}" />

As the binary data has to be converted back to an image object(?), and I'm lost on how to do that and conbine this with the bindings. Anyone have an idea?

Thanks for reading!

解决方案

You can create a converter to convert the value from byte[] to BitmapSource:

[ValueConversion(typeof(byte[]), typeof(BitmapSource))]
public class ByteArrayToImageConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        byte[] bytes = (byte[]) value;
        using (MemoryStream ms = new MemoryStream(bytes))
        {
            BitmapImage image = new BitmapImage();
            image.BeginInit();
            image.StreamSource = ms;
            image.EndInit();
            return image;
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        BitmapSource image = (BitmapSource) value;
        BitmapEncoder encoder = new PngBitmapEncoder();
        encoder.Frames.Add(BitmapFrame.Create(image));
        using (MemoryStream ms = new MemoryStream())
        {
            encoder.Save(ms);
            return ms.ToArray();
        }
    }
}

(The ConvertBack method encodes to PNG, you might want to change that depending on your needs. Or you might not need ConvertBack at all...)

这篇关于如何从SQL Server数据库检索图像到WPF窗体? (LINQ,数据绑定,SQL)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆