SeD
SeD

Reputation: 13

Display an image stored in MySql database in BLOB format using c#

I am using the following function to store image in db

 void SaveImage(byte[] image)
        {
            MySqlConnection con = new MySqlConnection(db);//new connection is made
            con.Open();

                string cmdText = "INSERT INTO Picture(RoomNo ,pic )VALUES ('" + RoomNo.Text + "',?Image)";
                MySqlCommand cmd = new MySqlCommand(cmdText, con);
                cmd.Parameters.Add("?Image", image);
                cmd.ExecuteNonQuery();
         
        }

In main I am calling the function like this

 using (var ms = new MemoryStream())
            {
                picbox.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                SaveImage(ms.ToArray());
            }

I do not know how to display it in a picture box .. can any one help me???

Upvotes: 1

Views: 8374

Answers (2)

Farhad Jabiyev
Farhad Jabiyev

Reputation: 26665

Are you using Windows Forms? And you must Convert Byte array to Image for displaying it in Picture Box.

public Image byteArrayToImage(byte[] byteArrayIn)
{
    MemoryStream ms = new MemoryStream(byteArrayIn);
    Image returnImage = Image.FromStream(ms);
    return returnImage;
}

And how did you convert Image to byte array. I hope that problem not there. You can use:

  private byte[] ImageToByteArray(string ImageFile)
    {
        FileStream stream = new FileStream(
              ImageFile, FileMode.Open, FileAccess.Read);
        BinaryReader reader = new BinaryReader(stream);

        // Convert image to byte array.
        byte[] photo = reader.ReadBytes((int)stream.Length);

        return photo;
    }

Upvotes: 5

Hassan Boutougha
Hassan Boutougha

Reputation: 3919

set your image picture box using Image method (FromStream)

  yourPictureBox.Image = Image.FromStream(ms); 

Upvotes: 0

Related Questions