为网站图片添加水印

来源:互联网 发布:百策早教管理软件 编辑:程序博客网 时间:2024/04/30 22:03

1.为网站添加一个类,例如命名sq.cs,注意要放到App_Code目录中.

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Drawing;
using System.IO;

/// <summary>
/// ImgHandler 的摘要说明
/// </summary>
public class sq : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "image/jpeg";
        string imgfile = context.Request.PhysicalPath;
        Image img1 = null;
        Graphics g = null;
        if (File.Exists(imgfile))
        {
            //原图片
            img1 = Image.FromFile(imgfile);
            //水印图片
            //Image img2 = Image.FromFile(context.Server.MapPath("~//images//WaterMark.jpg"));
            //画布
             g = Graphics.FromImage(img1);
            //将水印图片画在原图片的右下角
            //g.DrawImage(img2, new Rectangle(img1.Width - img2.Width, img1.Height - img2.Height, img2.Width, img2.Height), 0, 0, img2.Width, img2.Height, GraphicsUnit.Pixel);

            //添加文字水印
            Font f = new Font("宋体", 12);
            Brush b = new SolidBrush(Color.Red);
            g.DrawString("www.t49.com", f, b, 100, 40);
            g.Dispose();
        }
        else
        {
            img1 = Image.FromFile(context.Server.MapPath("~//images//55.jpg"));
        }
        //保存加了水印的图片到response
        img1.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
        //释放资源
        //
        img1.Dispose();
        context.Response.End();//结束response
    }

    public bool IsReusable//是否复用(每次都实例一个对象)
    {
        get
        {
            return false;
        }
    }
}
2.在web.config备置文件中的<authentication mode="Windows"/>下添加如下代码:

<httpHandlers>
   <add verb="*" path="images/*.jpg" type="sq"/>
</httpHandlers>

意为只对images文件下的所有jpg图片才会调用sq.cs类进行水印处理,避免了对美化页面的图片处理.

原创粉丝点击