首页  >  文章  >  数据库  >  如何在 PictureBox 中检索并显示 MySQL 数据库中的图像?

如何在 PictureBox 中检索并显示 MySQL 数据库中的图像?

Patricia Arquette
Patricia Arquette原创
2024-10-28 05:39:30161浏览

How to Retrieve and Display Images from a MySQL Database in a PictureBox?

从 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中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn