新建ASP.NET Web应用程序WebSuiyin
然后在WebSuiyin中添加HttpHandler类 ,继承IHttpHandler接口 代码如下
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Web;
namespace WebSuiyin
{
public class TestHandler : IHttpHandler
{
//水印图片
private const string WATERMARK_URL = "~/Images/003.jpg";
//图片不存在,默认显示的图片
private const string DEFAULTIMAGE_URL = "~/Images/001.jpg";
public void ProcessRequest(HttpContext context)
{
//得到用户请求的图片
string filePath = context.Request.PhysicalPath;//请求路径
System.Drawing.Image Cover;
//判断请求的物理路径中是否存在文件
if (File.Exists(filePath))
{
//加载文件
Cover = Image.FromFile(filePath);
//加载水印图片
Image watermark = Image.FromFile(context.Server.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_URL));
}
//设置输出格式
context.Response.ContentType = "image/jpeg";
//将图片存入输出流
Cover.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
Cover.Dispose();
context.Response.End();
}
public bool IsReusable
{
get { return false; }
}
}
}
然后在WebSuiyin新建Images文件夹存放图片
然后在WebSuiyin中的Web.config中添加以下代码
<system.webServer>
<handlers>
<add verb="*" path="Images/*.jpg" name="handler" type="WebSuiyin.TestHandler"/>
</handlers>
</system.webServer>
然后在WebSuiyin新建一个web窗体 添加以下代码
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="WebSuiyin.Index" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<img src="Images/001.jpg" />
<img src="Images/003.jpg" />
</div>
</form>
</body>
</html>
然后运行
就好了。