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

Patricia Arquette
发布: 2024-10-28 05:39:30
原创
160 人浏览过

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

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!