用 Handler 给图片加水印
新建一个 Handler 类:
using System;
using System.Web;
using System.IO;
using System.Drawing;
public class Handler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
Image image;
string path = context.Request.PhysicalPath;
if (File.Exists(path))
{
image = Image.FromFile(path);
Graphics grp = Graphics.FromImage(image);
grp.DrawString("水印字样", new Font("宋体", 18), new SolidBrush(Color.Red), 50f, 50f);
image.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
context.Response.End();
grp.Dispose();
image.Dispose();
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
在配置文件中加上:
<httpHandlers>
<add verb="*" path="img/*.jpg" type="Handler"/>
</httpHandlers>
这样之后只要访问站点下 img 文件夹下的 jpg 或 jpeg 图片上面都会加上 “水印字样”
using System.Web;
using System.IO;
using System.Drawing;
public class Handler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
Image image;
string path = context.Request.PhysicalPath;
if (File.Exists(path))
{
image = Image.FromFile(path);
Graphics grp = Graphics.FromImage(image);
grp.DrawString("水印字样", new Font("宋体", 18), new SolidBrush(Color.Red), 50f, 50f);
image.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
context.Response.End();
grp.Dispose();
image.Dispose();
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
在配置文件中加上:
<httpHandlers>
<add verb="*" path="img/*.jpg" type="Handler"/>
</httpHandlers>
这样之后只要访问站点下 img 文件夹下的 jpg 或 jpeg 图片上面都会加上 “水印字样”

浙公网安备 33010602011771号