asp.net为图片加上水印
为我们发布的图片加上一个水印,也是我们经常要做的事情,那怎么样来做呢,下面就一步步开始吧
首先是一个制作水印的类:ImageHandler,代码如下:
C#代码
- usingSystem;
- usingSystem.IO;
- usingSystem.Drawing;
- usingSystem.Drawing.Imaging;
- usingSystem.Data;
- usingSystem.Configuration;
- usingSystem.Linq;
- usingSystem.Web;
- usingSystem.Web.Security;
- usingSystem.Web.UI;
- usingSystem.Web.UI.HtmlControls;
- usingSystem.Web.UI.WebControls.WebParts;
- usingSystem.xml.Linq;
- ///<summary>
- ///ImageHandler的摘要说明
- ///</summary>
- publicclassImageHandler:IHttpHandler
- {
- PRivateconststringwaterMark_URL="~/Images/waterMark.jpg";
- privateconststringdefaultImage_URL="~/Images/Default.jpg";
- publicImageHandler()
- {
- //
- //TODO:在此处添加构造函数逻辑
- //
- }
- publicvoidProcessRequest(HttpContextcontext)
- {
- System.Drawing.ImageImageConver;
- if(File.Exists(context.Request.PhysicalPath))
- {
- //加载文件
- ImageConver=Image.FromFile(context.Request.PhysicalPath);
- //加载水印图片
- ImagewaterMark=Image.FromFile(context.Request.MapPath(waterMark_URL));
- //重新画布
- Graphicsg=Graphics.FromImage(ImageConver);
- g.DrawImage(waterMark,newRectangle(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();
- }
- publicboolIsReusable
- {
- get
- {
- returnfalse;
- }
- }
- }
接下来,我们要做一个很关键的配置,那就是在Web.Config文件中加入如下一句话
<httpHandlers>
<!--图片水印--> <add verb="*" path="Images/*.jpg" type="ImageHandler"/>
</httpHandlers>