首页  >  文章  >  数据库  >  如何在 PictureBox 中显示 MySQL 中存储为 BLOB 的图像?

如何在 PictureBox 中显示 MySQL 中存储为 BLOB 的图像?

Patricia Arquette
Patricia Arquette原创
2024-10-28 17:55:02464浏览

How to Display an Image Stored as a BLOB in MySQL in a PictureBox?

如何从 MySQL 检索图像并将其显示在 PictureBox 中

问题:

检索存储为 BLOB 的图像在 MySQL 数据库中并在 PictureBox 中显示它们无法正常工作。

解决方案:

所提供代码中的问题在于从错误中检索图像数据库。以下步骤概述了从 MySQL 数据库检索和显示图像的方法:

  1. 数据库设置:

    • 创建表MySQL 数据库,有一列将图像数据存储为 BLOB 类型。
  2. 在 PictureBox 中显示图像:

    • 在 byteArrayToImage 方法中,将字节数组 (ImageByte) 转换为 Image 对象:

      public Image byteArrayToImage(byte[] byteArrayIn)
      {
          using (var ms = new MemoryStream(byteArrayIn))
          {
              return Image.FromStream(ms);
          }
      }
    • 在 photoLoad 方法中,使用参数化查询检索图像:

      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();
              }
          }
          // ...
      }
  3. 其他注意事项:

    • 确保图像正确保存到数据库中(例如,使用 File.ReadAllBytes 读取图像文件)。
    • 在尝试将检索到的字节数组 (ImageByte) 转换为 Image 对象之前检查其是否不为空。
    • 适当处理异常在 photoLoad 方法中进行错误处理。

以上是如何在 PictureBox 中显示 MySQL 中存储为 BLOB 的图像?的详细内容。更多信息请关注PHP中文网其他相关文章!

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