Home >Database >Mysql Tutorial >How to Display an Image Stored as a BLOB in MySQL in a PictureBox?
Problem:
Retrieving images stored as BLOBs in a MySQL database and displaying them in a PictureBox is not working correctly.
Solution:
The issue in the provided code lies in the incorrect retrieval of the image from the database. The following steps outline a method to retrieve and display images from a MySQL database:
Database Setup:
Display Image in PictureBox:
In the byteArrayToImage method, convert the byte array (ImageByte) to an Image object:
public Image byteArrayToImage(byte[] byteArrayIn) { using (var ms = new MemoryStream(byteArrayIn)) { return Image.FromStream(ms); } }
In the photoLoad method, retrieve the image using a parameterized query:
private void photoLoad() { // ... using (var con = new MySqlConnection(connectionString)) { byte[] ImageByte = new byte[0]; string query1 = "select image from reg.img_table where id= @id"; using (var cmd = new MySqlCommand(query1, con)) { cmd.Parameters.AddWithValue("@id", Properties.Settings.Default.idImg); con.Open(); using (var row = cmd.ExecuteReader()) { while (row.Read()) { ImageByte = (byte[])(row["image"]); } } } if (ImageByte != null) { // Convert to an Image object and display in PictureBox roundPictureBox1.Image = byteArrayToImage(ImageByte); roundPictureBox1.Refresh(); } } // ... }
Additional Considerations:
The above is the detailed content of How to Display an Image Stored as a BLOB in MySQL in a PictureBox?. For more information, please follow other related articles on the PHP Chinese website!