从 MySQL 检索图像并在 PictureBox 中显示
要从 MySQL 数据库检索图像并将其显示在 PictureBox 中,请按照以下步骤操作:
1。将图像添加到数据库:
<code class="csharp">using(OpenFileDialog ofd = new OpenFileDialog()) { if (ofd.ShowDialog() == DialogResult.OK) { byte[] bytes = File.ReadAllBytes(ofd.FileName); string imageUrl = ofd.FileName.ToString(); MySqlConnection con = new MySqlConnection(connectionString); con.Open(); // Insert image into database MySqlCommand cmd = new MySqlCommand("INSERT INTO reg.img_table(image, id) VALUES (@image, @id)", con); long id = cmd.LastInsertedId; cmd.Parameters.AddWithValue("@image", bytes); cmd.Parameters.AddWithValue("@id", id); cmd.ExecuteNonQuery(); con.Close(); } }</code>
2.从数据库检索图像:
<code class="csharp">private Image byteArrayToImage(byte[] byteArrayIn) { MemoryStream ms = new MemoryStream(byteArrayIn); Image returnImage = Image.FromStream(ms); return returnImage; } private void photoLoad() { string connectionString = ...; MySqlConnection con = new MySqlConnection(connectionString); byte[] ImageByte = new byte[0]; string query1 = "select image from reg.img_table where id= @id"; MySqlCommand cmd = new MySqlCommand(query1, con); cmd.Parameters.AddWithValue("@id", ...); con.Open(); MySqlDataReader row; row = cmd.ExecuteReader(); while (row.Read()) { ImageByte = (Byte[])(row["image"]); } con.Close(); if (ImageByte != null) { // Convert to bitmap and display in PictureBox roundPictureBox1.Image = byteArrayToImage(ImageByte); roundPictureBox1.Refresh(); } }</code>
确保您的连接字符串正确,并且您已使用适当的列创建了数据库表 img_table。提供的代码应该可以在 PictureBox 中检索和显示图像。
以上是如何在 PictureBox 中检索并显示 MySQL 数据库中的图像?的详细内容。更多信息请关注PHP中文网其他相关文章!