简体   繁体   中英

How to retrieve Image from MySQL database using C#

I am trying to retrieve an image on Form load using function command but it does not load and I get an error "Parameter is not valid". Please check where I am wrong in the code because I tried to debug my code via break points and it is showing me that code is working fine, but somewhere image is not retrieved from database to picture box.

Here is my code:

public static Bitmap ByteToImage(byte[] blob)
{
        MemoryStream mStream = new MemoryStream();
        byte[] pData = blob;
        mStream.Write(pData, 0, Convert.ToInt32(pData.Length));
        Bitmap bm = new Bitmap(mStream, false);
        mStream.Dispose();
        return bm;
}

Retrieve image using Photoload function:

public void photoLoad()
{
        ConnectionDB cnn = new ConnectionDB();

        string query1 = "select image from doctor_image where do='" + DoctorPanel.drUsername + "'";

        try
        {
            cnn.Open();
            MySqlDataReader row;
            row = cnn.ExecuteReader(query1);

            while (row.Read())
            {
                ImageByte = (Byte[])(row["image"]);
            }

            if (ImageByte != null)
            {
                // You need to convert it in bitmap to display the image
                pictureBox1.Image = ByteToImage(ImageByte);
                pictureBox1.Refresh();
            }
        }
        catch (Exception ex)
        {
           MessageBox.Show(ex.Message);
        }
}

Insert into database

private void Button6_Click(object sender, EventArgs e)
{
        OpenFileDialog open = new OpenFileDialog();

        // image filters  
        open.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp)|*.jpg; *.jpeg; *.gif; *.bmp";

        if (open.ShowDialog() == DialogResult.OK)
        {
            // display image in picture box  
            //pictureBox1.Image = new Bitmap(open.FileName);
            pictureBox1.Image = Image.FromFile(open.FileName);

            ConnectionDB cnn = new ConnectionDB();
            cnn.Open();

            string sql = "INSERT INTO doctor_image(image, do) VALUES('" + pictureBox1.Image + "','" + DoctorPanel.drUsername + "')";
            int noofrows = cnn.ExecuteNonQuery(sql);

            if (noofrows != -1)
            {
                MessageBox.Show("Photo uploaded");
            }
            else
            {
                MessageBox.Show("Data insert error");
            }
        }
}

This line of code is wrong:

string sql = "INSERT INTO doctor_image(image, do) VALUES('" + pictureBox1.Image + "','" + DoctorPanel.drUsername + "')";

Firstly, you're using string concatenation to build the SQL. This is a common source of security problems (specifically, SQL injection). Use parameters instead.

Secondly, "'" + pictureBox1.Image + "','" will simply output a string similar to 'System.Drawing.Bitmap' which will be inserted into your database. This is obviously not a valid image, which is why you get the "Parameter is not valid" exception when you try to load it.

It looks like you just want to insert the bytes of the image into your database, which has a simple fix. You don't even need to use the Image class; simply read the bytes of the file and load them into the table:

using (var cmd = new MySqlCommand(@"INSERT INTO doctor_image(image, do) VALUES(@image, @do);", cnn)
{
    cmd.Parameters.AddWithValue("@image", File.ReadAllBytes(open.FileName));
    cmd.Parameters.AddWithValue("@do", DoctorPanel.drUsername);
    cmd.ExecuteNonQuery();
}

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