为我们发布的图片加上一个水印,也是我们经常要做的事情,那怎么样来做呢,下面就一步步开始吧
首先是一个制作水印的类:ImageHandler,代码如下:
- using System;
- using System.IO;
- using System.Drawing;
- using System.Drawing.Imaging;
- using System.Data;
- using System.Configuration;
- using System.Linq;
- using System.Web;
- using System.Web.Security;
- using System.Web.UI;
- using System.Web.UI.HtmlControls;
- using System.Web.UI.WebControls.WebParts;
- using System.Xml.Linq;
- /// <summary>
- ///ImageHandler 的摘要说明
- /// </summary>
- public class ImageHandler:IHttpHandler
- {
- private const string waterMark_URL = "~/Images/waterMark.jpg";
- private const string defaultImage_URL = "~/Images/Default.jpg";
- public ImageHandler()
- {
- //
- //TODO: 在此处添加构造函数逻辑
- //
- }
- public void ProcessRequest(HttpContext context)
- {
- System.Drawing.Image ImageConver;
- if (File.Exists(context.Request.PhysicalPath))
- {
- //加载文件
- ImageConver = Image.FromFile(context.Request.PhysicalPath);
- //加载水印图片
- Image waterMark = Image.FromFile(context.Request.MapPath(waterMark_URL));
- //重新画布
- Graphics g = Graphics.FromImage(ImageConver);
- g.DrawImage(waterMark, new Rectangle(ImageConver.Width - waterMark.Width, ImageConver.Height - waterMark.Height, waterMark.Width, waterMark.Height), 0, 0, waterMark.Width, waterMark.Height, GraphicsUnit.Pixel);
- g.Dispose();
- waterMark.Dispose();
- }
- else
- {
- ImageConver=Image.FromFile(context.Request.MapPath(defaultImage_URL));
- }
- //设置输出格式
- context.Response.ContentType="image/jpeg";
- ImageConver.Save(context.Response.OutputStream,System.Drawing.Imaging.ImageFormat.Jpeg);
- ImageConver.Dispose();
- context.Response.End();
- }
- public bool IsReusable
- {
- get
- {
- return false;
- }
- }
- }
接下来,我们要做一个很关键的配置,那就是在Web.Config文件中加入如下一句话
<httpHandlers>
<!--图片水印-->
<add verb="*" path="Images/*.jpg" type="ImageHandler"/>
</httpHandlers>