專案需求:使用者上傳產品圖片時,伺服器自動加入公司版權浮水印,避免人工後製。利用 System.Drawing 命名空間 (GDI+) 即可輕鬆實現。
private void AddTextToImg(string fileName, string text)
{
if (!File.Exists(Server.MapPath(fileName)))
throw new FileNotFoundException("檔案不存在");
if (string.IsNullOrEmpty(text)) return;
// 1. 載入原圖
using (Image img = Image.FromFile(Server.MapPath(fileName)))
using (Bitmap bmp = new Bitmap(img.Width, img.Height))
using (Graphics g = Graphics.FromImage(bmp))
{
// 2. 繪製原圖
g.DrawImage(img, 0, 0, img.Width, img.Height);
// 3. 設定字體與筆刷
float fontSize = 12f;
Font font = new Font("微軟正黑體", fontSize, FontStyle.Bold);
Brush bgBrush = new SolidBrush(Color.FromArgb(128, 0, 0, 0)); // 半透明黑底
Brush txtBrush = new SolidBrush(Color.White);
// 4. 計算文字區域 (右下角)
SizeF txtSize = g.MeasureString(text, font);
float x = bmp.Width - txtSize.Width - 10;
float y = bmp.Height - txtSize.Height - 10;
RectangleF rect = new RectangleF(x - 5, y - 2, txtSize.Width + 10, txtSize.Height + 4);
// 5. 繪製背景矩形 + 文字
g.FillRectangle(bgBrush, rect);
g.DrawString(text, font, txtBrush, x, y);
// 6. 輸出至 Response (或存檔)
Response.Clear();
Response.ContentType = "image/jpeg";
using (MemoryStream ms = new MemoryStream())
{
bmp.Save(ms, ImageFormat.Jpeg);
ms.WriteTo(Response.OutputStream);
}
}
}
Image、Bitmap、Graphics、Font、Brush 等非受控資源及時釋放,防止 GDI+ 物件洩漏導致「一般性錯誤」。Color.FromArgb(128, 0, 0, 0) 讓浮水印不遮蔽圖片細節。protected void btnUpload_Click(object sender, EventArgs e)
{
if (fuImage.HasFile)
{
string savePath = "~/Uploads/" + Guid.NewGuid() + Path.GetExtension(fuImage.FileName);
fuImage.SaveAs(Server.MapPath(savePath));
AddTextToImg(savePath, "Copyright © 2024 MyCompany"); // 即時加浮水印並輸出預覽
// 或:另存處理後圖片 bmp.Save(Server.MapPath(savePath), ImageFormat.Jpeg);
}
}
此方案零第三方元件、部署簡單、效能足夠支援中小型網站上傳量,是 ASP.NET 圖片處理的經典最佳實踐。