首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

C# 讀取 MySQL BLOB 圖片:Byte 數組長度不全,原因是錯誤調用 ToString()

     編輯:程式設計綜合問答

問題現象

資料庫 BLOB 欄位存入 23817 位元組,讀取時 byte[] bs = (byte[])dr[8] 僅得 255 位元組,導致圖片損壞無法顯示。

錯誤代碼

byte[] bs = (byte[])thisreader["image"].ToString(); // 錯誤:ToString() 將 byte[] 轉為 "System.Byte[]"

正確讀取方式

// 1. 直接強制轉型(推薦)
byte[] bs = (byte[])dr["image"]; // 或 dr.GetValue(8)

// 2. 處理 DBNull
byte[] bs = dr["image"] as byte[]; // 若為 NULL 返回 null

// 3. 顯式 GetBytes(大物件分塊讀取)
long len = dr.GetBytes(8, 0, null, 0, 0);
byte[] bs = new byte[len];
dr.GetBytes(8, 0, bs, 0, (int)len);

完整顯示範例

byte[] bs = (byte[])dr["image"];
using (MemoryStream ms = new MemoryStream(bs)) {
    pictureBox1.Image = Image.FromStream(ms);
}

存入參考

using (MemoryStream ms = new MemoryStream()) {
    image.Save(ms, ImageFormat.Jpeg);
    byte[] bs = ms.ToArray();
    // 參數化 SQL: INSERT INTO t(img) VALUES (@img)
    cmd.Parameters.Add("@img", MySqlDbType.Blob).Value = bs;
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved