using System;
using System.Web;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
public class Handler : IHttpHandler
{
//水印图片路径
private const string WATERMARK_URL = "~/Images/watermark.jpg";
//默认图片路径
private const string DEFAULTIMAGE = "~/Images/default.jpg";
public void ProcessRequest(HttpContext context)
{
Image Cover;
//判断请求的物理路径,图片是否存在
if (File.Exists(context.Request.PhysicalPath))
{
//加载文件
Cover = Image.FromFile(context.Request.PhysicalPath);
//加载水印图片
Image watermark = Image.FromFile(context.Request.MapPath(WATERMARK_URL));
//实例化画布
Graphics g = Graphics.FromImage(Cover);
//在Image上绘制水印
g.DrawImage(watermark, new Rectangle(Cover.Width - watermark.Width, Cover.Height - watermark.Height, watermark.Width, watermark.Height), 0, 0, watermark.Width, watermark.Height, GraphicsUnit.Pixel);
//释放画布
g.Dispose();
//释放水印图片
watermark.Dispose();
}
else
{
//默认图片
Cover = Image.FromFile(context.Request.MapPath(DEFAULTIMAGE));
}
//设置输出格式
context.Response.ContentType = "image/jpeg";
//把绘制好的图片保存到输出流中
Cover.Save(context.Response.OutputStream, ImageFormat.Jpeg);
Cover.Dispose();
context.Response.End();
}
public bool IsReusable
{
get
{
return false;
}
}
}
/*
* 在配置文件中配置全局水印图片
*<system.web>
*<httpHandlers>
*<add verb="*" path="Images/BookCovers/*.jpg" type="Handler"/>
*</httpHandlers>
*</system.web>
*如果想在handler中使用Session需要引入一个
*using System.Web.SessionState;在实现一个IRequiresSessionState接口
*/
全局水印图片
最新推荐文章于 2023-07-27 00:17:27 发布