首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> 關於C#

C# 讀寫 SQL Server 圖片欄位:Image 型別與 Byte 陣列、MemoryStream、Bitmap 完整實戰

     編輯:關於C#

資料庫圖片存取核心流程

SQL Server image 型別(或較新 varbinary(max))存儲二進位位元組陣列。C# 存取關鍵類別:

  • byte[]:資料載體
  • MemoryStream:記憶體串流,橋接位元組陣列與影像物件
  • Bitmap / Image:GDI+ 影像處理
  • PictureBox:WinForms 顯示控制項

讀取並顯示圖片

private void ShowImage(DataSet ds, int rowIndex, PictureBox picBox) {
    byte[] bytes = (byte[])ds.Tables[0].Rows[rowIndex]["ImageColumn"];
    using (var ms = new MemoryStream(bytes)) {
        try {
            picBox.Image = new Bitmap(ms);
        } catch {
            picBox.Image = null; // 資料損壞或非圖片格式
        }
    }
}

從檔案讀取並寫入資料庫

private byte[] LoadImageFromFile(string path) {
    using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read)) {
        byte[] buffer = new byte[fs.Length];
        fs.Read(buffer, 0, buffer.Length);
        return buffer;
    }
}

// 更新 DataSet
ds.Tables[0].Rows[selectedIndex]["ImageColumn"] = LoadImageFromFile(openFileDialog.FileName);
ShowImage(ds, selectedIndex, pictureBox1);

完整 WinForms 範例架構

命名空間與欄位

using System.Data;
using System.Data.SqlClient;
using System.IO;

private string _connStr = "server=localhost;integrated security=sspi;database=pubs";
private SqlConnection _conn;
private SqlDataAdapter _adapter;
private DataSet _ds;

表單初始化:載入資料、綁定列表


private void Form_Load(object sender, EventArgs e) {
    string sql = "SELECT * FROM pub_info";
    _conn = new SqlConnection(_connStr);
    _adapter = new SqlDataAdapter(sql, _conn);
    new SqlCommandBuilder(_adapter); // 自動生成 Insert/Update/Delete
    _adapter.UpdateCommand = _adapter.UpdateCommand; // 確保命令就緒

    _ds = new DataSet();
    _adapter.Fill(_ds, "pub_info");

    // 綁定文字欄位
    textBox1.DataBindings.Add("Text", _ds, "pub_info.pr_info");

    // 填充列表框(顯示主鍵)
    foreach (DataRow row in _ds.Tables[0].Rows)
        listBox1.Items.Add(row[0]);
}

列表選擇切換顯示


private void listBox1_SelectedIndexChanged(object sender, EventArgs e) {
    ShowImage(_ds, listBox1.SelectedIndex, pictureBox1);
    BindingContext[_ds, "pub_info"].Position = listBox1.SelectedIndex;
}

更換圖片


private void btnChangeImage_Click(object sender, EventArgs e) {
    if (openFileDialog1.ShowDialog() == DialogResult.OK) {
        byte[] imgBytes = LoadImageFromFile(openFileDialog1.FileName);
        _ds.Tables[0].Rows[listBox1.SelectedIndex]["ImageColumn"] = imgBytes;
        ShowImage(_ds, listBox1.SelectedIndex, pictureBox1);
    }
}

移除圖片


private void btnRemoveImage_Click(object sender, EventArgs e) {
    _ds.Tables[0].Rows[listBox1.SelectedIndex]["ImageColumn"] = new byte[0]; // 或 DBNull.Value
    pictureBox1.Image = null;
}

儲存變更回資料庫


private void btnSave_Click(object sender, EventArgs e) {
    _adapter.Update(_ds, "pub_info");
    MessageBox.Show("儲存成功");
}

關鍵注意事項

  • 大型圖片:image 型別上限 2GB,但建議壓縮或改用檔案系統存儲路徑。
  • 資料綁定:SqlCommandBuilder 需主鍵欄位才能自動生成更新命令。
  • 例外處理:Bitmap 建構子對格式敏感,務必 try/catch。
  • 資源釋放:MemoryStream、FileStream、Bitmap 皆實作 IDisposable,善用 using。

現代化建議

新專案優先使用 varbinary(max) 取代已淘汰的 image 型別;考慮 Entity Framework Core 等 ORM 簡化資料存取;大量圖片場景評估 FileTable、Filestream 或雲端儲存(Blob Storage)。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved