0

After quite some time of trying and looking arround here for some answers, i am unable to load an image from MySQL.

Basicly, a user choses a picture from and OpenFileDialog which is then loaded in a PictureBox (this works fine).
Then the user clicks a button which will save the picture in the db by converting it to a byte[].
Finally, when I try to load the picture in another PictureBox, it's all black.

When adding the picture to the db:

public void PictureToDB(Image img)
{
    MemoryStream tmpStream = new MemoryStream();
    img.Save(tmpStream, ImageFormat.Png);
    tmpStream.Seek(0, SeekOrigin.Begin);
    byte[] imgBytes = new byte[5000];
    tmpStream.Read(imgBytes, 0, 5000);

    string query = "Update TABLE Set IMG = @imgBytes";
    MySqlParameter param = new MySqlParameter("@img", imgBytes);

    //Skipping connection to db and all... it works
}

Getting picture from db:

public void DBToPicture()
{
    string query = "Select IMG From TABLE Where ...";
    //Skipping Command lines ...
    MySqlDataReader reader = command.ExecuteReader();
    DataTable myDT.Load(reader);

    Byte[] data = new Byte[0];
    data = (Byte[])(myDT.Rows[0]["PHOTOLOISANT"]);
    MemoryStream mem = new MemoryStream(data);
    MyPictureBox.Image = Image.FromStream(mem);
}

More info:

  • the type in MySQL is varbinary(8000) and contains this "89504e470d0a1a0a0000000d4948445200000280000001e00802000000bab34bb3000000017352474200aece1ce90000000467414d41002e2e2e" after the update
  • the image is converted to bitmap when it is loaded in the first PictureBox.
Elliott Addi
  • 370
  • 4
  • 18
  • does the picture have to be stored into the database? – Chester Cobus Mar 24 '17 at 19:07
  • 1
    Please read this : http://stackoverflow.com/questions/815626/to-do-or-not-to-do-store-images-in-a-database and your IMG should be BLOB not varbinary(8000), when you use BLOB allows you to store it as binary data then it will be retrieved as byte[] – Chester Cobus Mar 24 '17 at 19:14
  • @ChesterCobus It doesn't have to be in the db, but i want it to. Just because i want to know how it works – Elliott Addi Mar 24 '17 at 19:15
  • 1
    Hope this helps : https://www.aspsnippets.com/Articles/Save-and-Retrieve-BLOB-Images-from-MySql-Database-in-ASPNet-C-and-VBNet.aspx – Chester Cobus Mar 24 '17 at 19:24
  • @ChesterCobus thanks for mentionning it was in BLOB btw! – Elliott Addi Mar 24 '17 at 19:34

1 Answers1

1

For storing:

conn = new MySqlConnection("server=" + hostname + ";uid=" + username + ";pwd=" + password + ";database=databaseimage;Charset=latin1;");
            conn.Open();
            FileStream fs;
            Byte[] bindata;
            MySqlParameter picpara;
            cmd = new MySqlCommand("INSERT INTO mypic (pic) VALUES(?pic)", conn);
            picpara = cmd.Parameters.Add("?pic", MySqlDbType.MediumBlob);
            cmd.Prepare();

//txtPicPath is the path of the image, e.g. C:\MyPic.png

            fs = new FileStream(txtPicPath.Text, FileMode.Open, FileAccess.Read);
            bindata = new byte[Convert.ToInt32(fs.Length)];
            fs.Read(bindata, 0, Convert.ToInt32(fs.Length));
            fs.Close();

            picpara.Value = bindata;
            cmd.ExecuteNonQuery();

To retrieve it:

if (conn == null) // Just to make sure that the connection was not severed
        {


                conn = new MySqlConnection("server=" + hostname + ";uid=" + username + ";pwd=" + password + ";database=databaseimage;Charset=latin1;");
                conn.Open();

        }
        MemoryStream ms = new MemoryStream();
        FileStream fs;
        Byte[] bindata;

        cmd = new MySqlCommand("SELECT pic FROM mypic WHERE id=3", conn);
        bindata = (byte[])(cmd.ExecuteScalar());



        ms.Write(bindata, 0, bindata.Length);
        pb2.Image = new Bitmap(ms);

        fs = new FileStream(name, FileMode.Create, FileAccess.Write);
        ms.WriteTo(fs);

I will use these kinda steps to store and retrieve image from MySql.

Sincerely,

Thiyagu Rajendran

**Please mark the replies as answers if they help and unmark if they don't.

  • I had to use `binData = new byte[Convert.ToInt32(fs.Length)-1];` and `fs.Read(binData, 0, Convert.ToInt32(fs.Length)-1);` for it to work, else I had an error. But now it works great, thanks a lot! cheers – Elliott Addi Mar 24 '17 at 19:32