user3718026
user3718026

Reputation: 13

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

Upvotes: 0

Views: 2639

Answers (2)

Yair Nevet
Yair Nevet

Reputation: 13003

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

Upvotes: 2

BlaugranaGent
BlaugranaGent

Reputation: 100

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

Upvotes: 0

Related Questions