简体   繁体   中英

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

This is what i tried to do but i don't know how to continue. PS. It's in 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:

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 :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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