如何在 PictureBox 中顯示 MySQL 中儲存為 BLOB 的圖片?

Patricia Arquette
發布: 2024-10-28 17:55:02
原創
463 人瀏覽過

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

如何從MySQL 擷取映像並將其顯示在PictureBox 中

問題:

擷取儲存為BLOB 的影像在MySQL 資料庫中並在PictureBox 中顯示它們無法正常運作。

解決方案:

所提供程式碼中的問題在於從錯誤中擷取影像資料庫。以下步驟概述了從MySQL 資料庫擷取和顯示影像的方法:

  1. 資料庫設定:

    • 建立表格,有一表列將影像資料儲存為BLOB 類型。
  2. 在PictureBox 中顯示圖片:

    • 在byteArrayToImage 組中,將位元組數) 轉換為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();
              }
          }
          // ...
      }
      登入後複製
其他注意事項:確保映像正確儲存到資料庫中(例如,使用File.ReadAllBytes 讀取映像檔)。 在嘗試將檢索到的位元組數組 (ImageByte) 轉換為 Image 物件之前檢查其是否不為空。 適當處理異常在 photoLoad 方法中進行錯誤處理。

以上是如何在 PictureBox 中顯示 MySQL 中儲存為 BLOB 的圖片?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!