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

ASP.NET 圖片動態加浮水印與防盜鏈 HttpHandler 完整實作

     編輯:ASP.NET 基礎

前言

透過 IHttpHandler 攔截圖片請求,可在伺服器端動態繪製浮水印並驗證 Referer 實現防盜鏈。本文提供兩種實作:簡易版與可設定 XML 版,並說明 web.config 註冊方式。

核心架構

  • 實作 IHttpHandler,於 ProcessRequest 中處理。
  • web.config 映射副檔名(.jpg/.png/.gif)至 Handler。
  • 判斷 Request.UrlReferrer.Host 是否為本站域名。
  • 本站請求 → 回傳原圖或加浮水印後輸出。
    外站請求 → 回傳警告圖片或文字。

簡易版 Handler

public class WatermarkHandler : IHttpHandler
{
    public bool IsReusable => true;

    public void ProcessRequest(HttpContext context)
    {
        var req = context.Request;
        var res = context.Response;

        // 防盜鏈:檢查 Referer
        if (req.UrlReferrer != null && req.UrlReferrer.Host.Equals(req.Url.Host, StringComparison.OrdinalIgnoreCase))
        {
            // 本站請求:加文字浮水印
            using (var img = Image.FromFile(req.PhysicalPath))
            using (var g = Graphics.FromImage(img))
            {
                g.DrawString("三國演義", new Font("宋體", 20, FontStyle.Bold), Brushes.White, 10, 10);
                img.Save(res.OutputStream, ImageFormat.Jpeg);
            }
            res.Flush();
            res.End();
        }
        else
        {
            // 盜鏈:回傳提示
            res.Write("您不能盜鏈本站圖片");
        }
    }
}

web.config 註冊 (IIS 7+ 整合模式)

<system.webServer>
  <handlers>
    <add name="WatermarkJpg" verb="*" path="*.jpg" type="YourNamespace.WatermarkHandler, YourAssembly" />
    <add name="WatermarkPng" verb="*" path="*.png" type="YourNamespace.WatermarkHandler, YourAssembly" />
    <add name="WatermarkGif" verb="*" path="*.gif" type="YourNamespace.WatermarkHandler, YourAssembly" />
  </handlers>
</system.webServer>

舊版 IIS 6/Classic 模式請用 <httpHandlers> 區段。

進階可設定版:XML 驅動浮水印參數

WaterMarkConfig.xml:

<watermark>
  <allowhost>localhost:6219</allowhost>
  <isflag>true</isflag>
  <type>font</type>              <!-- img 或 font -->
  <files>/config|/upfiles/ab</files> <!-- 需加浮水印的虛擬路徑關鍵字 -->
  <position>bottom-right</position>
  <img-path>~/UpFiles/Watermark.png</img-path>
  <font-style>1</font-style>        <!-- 0=一般 1=粗體 2=斜體 4=底線 8=刪除線 -->
  <font-size>60</font-size>
  <font-color>red</font-color>
  <font-content>¥:8000元</font-content>
  <errimgpath>images/error.jpg</errimgpath>
</watermark>

Handler 讀取 XML,依設定決定:

  • 是否加浮水印(isflag + 路徑比對)。
  • 浮水印類型:圖片(DrawImage)或文字(DrawString)。
  • 位置計算:支援四角與自動縮放。
  • 盜鏈回傳:指定錯誤圖片路徑。

關鍵輔助方法:位置計算

private Rectangle SetImgPosition(string pos, int w, int h, int wmW, int wmH)
{
    int margin = 10;
    double scale = 1;
    // 自動縮放邏輯...
    switch (pos)
    {
        case "top-left": return new Rectangle(margin, margin, wmW, wmH);
        case "top-right": return new Rectangle(w - margin - wmW, margin, wmW, wmH);
        case "bottom-left": return new Rectangle(margin, h - margin - wmH, wmW, wmH);
        default: return new Rectangle(w - margin - wmW, h - margin - wmH, wmW, wmH); // bottom-right
    }
}

文字版對應 SetFontPosition 回傳 Point。

資源釋放注意事項

  • 必須呼叫 Dispose() 釋放 Image、Graphics、Brush、Font 等非受控資源。
  • 使用 using 區塊確保例外時也能釋放。
  • 避免在高併發下產生大量 GDI+ 物件導致「一般性錯誤」。

總結

HttpHandler 實現圖片動態處理,零修改前端頁面即可全站套用浮水印與防盜鏈。生產環境建議搭配輸出快取(OutputCache)降低 CPU 壓力。

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