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

ASP.NET GDI+ 動態為圖片加浮水印:上傳即時處理、版權保護完整實作

     編輯:關於ASP.NET

專案需求:使用者上傳產品圖片時,伺服器自動加入公司版權浮水印,避免人工後製。利用 System.Drawing 命名空間 (GDI+) 即可輕鬆實現。

核心實作:AddTextToImg 方法

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);
        }
    }
}

關鍵技術點

  • using 區塊:確保 Image、Bitmap、Graphics、Font、Brush 等非受控資源及時釋放,防止 GDI+ 物件洩漏導致「一般性錯誤」。
  • 半透明背景:Color.FromArgb(128, 0, 0, 0) 讓浮水印不遮蔽圖片細節。
  • MeasureString:精確計算文字寬高,支援任意長度、字體大小自動換行邏輯擴充。
  • MemoryStream 輸出:避免落地暫存檔,直接輸出至 HTTP 回應,效能最佳。

整合至上傳流程

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 圖片處理的經典最佳實踐。

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