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

ASP.NET 使用 IHttpHandler 實作動態圖片浮水印

     編輯:關於ASP.NET

網站圖片加浮水印可防盜圖並達到宣傳效果。若逐張用 Photoshop 處理工程龐大且不可逆。利用 IHttpHandler 動態輸出帶浮水印的圖片,優點:修改一次全站生效、不異動原始圖檔、可依條件決定是否加浮水印。

兩種實作策略

  • 區域 Handler:針對特定圖片或資料夾,呼叫時需指定 Handler 路徑(如 <asp:Image ImageUrl="~/Watermark.ashx?id=123" />),彈性高但維護成本較大。
  • 全域 Handler:攔截特定路徑下所有圖片請求,自動加浮水印,維護簡單但彈性較低。

本文示範區域 Handler 作法。

完整程式碼:MyBookHandler.ashx

<%@ WebHandler Language="C#" Class="MyBookHandler" %>

using System;
using System.Web;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

public class MyBookHandler : IHttpHandler {
    private string imagePath = "~/images/";           // 原圖資料夾
    private const string waterImage = "~/images/watermark.png"; // 浮水印圖
    private const string defaultImage = "~/images/default.jpg"; // 找不到圖時的預設圖
    private const float alpha = 0.5f;                 // 浮水印透明度 0.0~1.0

    public void ProcessRequest(HttpContext context) {
        string imgName = context.Request.QueryString["imagename"] + ".jpg";
        string physicalPath = context.Request.MapPath(imagePath + imgName);
        Image sourceImg;

        if (File.Exists(physicalPath)) {
            sourceImg = Image.FromFile(physicalPath);
            using (Graphics g = Graphics.FromImage(sourceImg)) {
                Image watermark = Image.FromFile(context.Request.MapPath(waterImage));
                
                // 透明度色彩矩陣
                float[][] matrix = {
                    new float[] {1, 0, 0, 0, 0},
                    new float[] {0, 1, 0, 0, 0},
                    new float[] {0, 0, 1, 0, 0},
                    new float[] {0, 0, 0, alpha, 0},
                    new float[] {0, 0, 0, 0, 1}
                };
                ColorMatrix cm = new ColorMatrix(matrix);
                ImageAttributes attrs = new ImageAttributes();
                attrs.SetColorMatrix(cm, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);

                // 置於右下角
                int x = sourceImg.Width - watermark.Width;
                int y = sourceImg.Height - watermark.Height;
                g.DrawImage(watermark, new Rectangle(x, y, watermark.Width, watermark.Height),
                            0, 0, watermark.Width, watermark.Height, GraphicsUnit.Pixel, attrs);
                
                watermark.Dispose();
            }
        } else {
            sourceImg = Image.FromFile(context.Request.MapPath(defaultImage));
        }

        context.Response.ContentType = "image/jpeg";
        sourceImg.Save(context.Response.OutputStream, ImageFormat.Jpeg);
        sourceImg.Dispose();
        context.Response.End();
    }

    public bool IsReusable => false;
}

前端呼叫範例

<asp:Image ID="Image1" runat="server" 
    ImageUrl='~/MyBookHandler.ashx?imagename=9221944' />

進階應用建議

  • 快取機制:輸出前檢查 If-Modified-Since,回傳 304 Not Modified 減少頻寬。
  • 浮水印位置參數化:透過 QueryString 傳遞 position=tl|tr|bl|br|center。
  • 文字浮水印:改用 Graphics.DrawString 繪製動態文字(如使用者 ID、時間戳)。
  • 效能優化:將處理後圖片暫存至快取目錄,下次直接輸出靜態檔避免重複運算。

部署注意事項

  1. 確保 IIS 應用程式集區身分識別對圖片資料夾有讀取權限。
  2. web.config 中註冊 .ashx 對應 System.Web.UI.SimpleHandlerFactory(預設已支援)。
  3. 大量併發時考慮使用 OutputCache 或 CDN 緩解伺服器壓力。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved