using System;
using System.Web;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
/// <summary>
/// 映射文件后缀名方式的数字水印
/// </summary>
public class CoverHandler : IHttpHandler
{
//数字水印路径
private const string WATERMARK_URL = "~/Images/WaterMark.jpg";
//默认图片路径
private const string DEFAULT_PIC = "~/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);
//Cover上绘制水印
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(DEFAULT_PIC));
}
//设置输出格式
context.Response.ContentType = "image/jpeg";
//将图片存入输出流
Cover.Save(context.Response.OutputStream,ImageFormat.Jpeg);
//释放资源
Cover.Dispose();
//停止HTTP响应
context.Response.End();
}
public bool IsReusable
{
get
{
return false;
}
}
}
using System.Web;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
/// <summary>
/// 映射文件后缀名方式的数字水印
/// </summary>
public class CoverHandler : IHttpHandler
{
//数字水印路径
private const string WATERMARK_URL = "~/Images/WaterMark.jpg";
//默认图片路径
private const string DEFAULT_PIC = "~/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);
//Cover上绘制水印
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(DEFAULT_PIC));
}
//设置输出格式
context.Response.ContentType = "image/jpeg";
//将图片存入输出流
Cover.Save(context.Response.OutputStream,ImageFormat.Jpeg);
//释放资源
Cover.Dispose();
//停止HTTP响应
context.Response.End();
}
public bool IsReusable
{
get
{
return false;
}
}
}
通过实现IHttpHandler接口,自定义实现HTTP请求的处理
希望对于想要了解ASP.NET内部实现机制的朋友给予帮助