儲存圖片至資料庫 (VARBINARY/IMAGE/BLOB)
1. FileUpload 直接取得 Byte 陣列
byte[] fileData = FileUpload1.FileBytes; // .NET 2.0+
2. 從實體路徑讀取轉 Byte[]
public byte[] FileToBytes(string path)
{
using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
using (BinaryReader br = new BinaryReader(fs))
{
return br.ReadBytes((int)fs.Length);
}
}
3. Image 物件轉 Byte[] (如動態產生圖表)
public static byte[] ImageToBytes(Image img, ImageFormat format = null)
{
using (MemoryStream ms = new MemoryStream())
{
img.Save(ms, format ?? ImageFormat.Jpeg);
return ms.ToArray();
}
}
從資料庫讀取並顯示
方式一:回傳 Image 物件 (適用 WinForms / 報表元件)
private Image GetImageFromDb()
{
string sql = "SELECT IMGDATA FROM t_img WHERE imgID=100";
using (OracleConnection conn = new OracleConnection(connStr))
using (OracleCommand cmd = new OracleCommand(sql, conn))
{
conn.Open();
byte[] data = (byte[])cmd.ExecuteScalar();
using (MemoryStream ms = new MemoryStream(data))
return Image.FromStream(ms);
}
}
方式二:Generic Handler (.ashx) 直接輸出二進位流 (Web 最佳做法)
// ImageHandler.ashx
public class ImageHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string id = context.Request.QueryString["id"];
byte[] imgData = GetImageBytesFromDb(id); // 自行實作查詢
if (imgData != null && imgData.Length > 0)
{
context.Response.Clear();
context.Response.ContentType = "image/jpeg"; // 或依副檔名動態判斷
context.Response.BinaryWrite(imgData);
context.Response.End();
}
else
{
context.Response.StatusCode = 404;
}
}
public bool IsReusable => false;
}
前端引用
<img src="ImageHandler.ashx?id=100" alt="動態圖片" />
資料表設計建議
CREATE TABLE Images (
Id INT PRIMARY KEY IDENTITY,
FileName NVARCHAR(255),
ContentType VARCHAR(50), -- image/jpeg, image/png...
FileSize INT,
ImageData VARBINARY(MAX), -- SQL Server
-- BLOB / BYTEA (PostgreSQL/MySQL)
CreatedAt DATETIME DEFAULT GETDATE()
);
效能與架構建議
- 大量/大檔案圖片建議存檔案系統/物件儲存 (Azure Blob, S3),資料庫僅存路徑。
- 啟用 IIS 靜態內容快取、CDN 加速。
- 若必須存 DB,考慮
FILESTREAM (SQL Server) 或資料表分割。