網站圖片加浮水印可防盜圖並達到宣傳效果。若逐張用 Photoshop 處理工程龐大且不可逆。利用 IHttpHandler 動態輸出帶浮水印的圖片,優點:修改一次全站生效、不異動原始圖檔、可依條件決定是否加浮水印。
<asp:Image ImageUrl="~/Watermark.ashx?id=123" />),彈性高但維護成本較大。本文示範區域 Handler 作法。
<%@ 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 減少頻寬。position=tl|tr|bl|br|center。Graphics.DrawString 繪製動態文字(如使用者 ID、時間戳)。web.config 中註冊 .ashx 對應 System.Web.UI.SimpleHandlerFactory(預設已支援)。OutputCache 或 CDN 緩解伺服器壓力。