简体   繁体   English

C#WPF从MySQL显示图像

[英]C# WPF Show Image from Mysql

i'm a student and i am bad at programing. 我是一个学生,我编程不好。 I saved the images in my mysql database for each player. 我将图像保存在每个播放器的mysql数据库中。 I created a program where I can list some soccer players from my database. 我创建了一个程序,可以从数据库中列出一些足球运动员。 When i click on a listed player in datagrid, a new window appears with the information about the player. 当我单击datagrid中列出的播放器时,会出现一个新窗口,其中包含有关播放器的信息。 Everything works, but now i want a picture of the selected player to be displayed on the information window from the database. 一切正常,但是现在我希望所选播放器的图片从数据库显示在信息窗口中。 Can anybody help me? 有谁能够帮助我? My english is not the best (i'm 17) so i hope you can understand what i mean. 我的英语不是最好的(我17岁),所以我希望你能理解我的意思。

This is what i tried to do but i don't know how to continue. 这是我试图做的,但我不知道如何继续。 PS. PS。 It's in WPF. 在WPF中。

 MySqlCommand cmd = new MySqlCommand("SELECT Bilder FROM spieler WHERE Bilder='{8}'");
        MySqlDataReader rdr1 = cmd.ExecuteReader();

        try
        {
            conn.Open();
            while (rdr1.Read())
            {
                // image1... I don't know what to write here
            }

        }
        catch (Exception ex)
        {
            MessageBox.Show("Fehler: " + ex);
        }

        rdr1.Close()

Just get it using a byte[] casting beforehand: 只需使用byte[]强制转换即可获取它:

while (rdr1.Read())
{
   byte[] data = (byte[])reader[0]; // 0 is okay if you only selecting one column
   //And use:
   using (System.IO.MemoryStream ms = new System.IO.MemoryStream(data))
   {
      Image image = new Bitmap(ms);
   }
}

UPDATE: In WPF, use the BitmapImage : 更新:在WPF中,使用BitmapImage

using (System.IO.MemoryStream ms = new System.IO.MemoryStream(data))
{
    var imageSource = new BitmapImage();
    imageSource.BeginInit();
    imageSource.StreamSource = ms;
    imageSource.CacheOption = BitmapCacheOption.OnLoad;
    imageSource.EndInit();

    // Assign the Source property of your image
    yourImage.Source = imageSource;
}

What is column's type where you hold the image? 您保存图像的列的类型是什么? You could try somehing like this 你可以这样尝试

Image tmp = ImageConverter.ConvertFrom(rdr1.GetStream("photo"));

where photo is name of your column 照片是您专栏的名称

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM