图片加水印

防止图片被别人转载使用,我们会对图片进行水印处理。

<%@ WebHandler Language="C#" Class="BookHandler" %>

using System;

using System.Web;

using System.Drawing;

using System.IO;

 

public class BookHandler : IHttpHandler {

    private const string COVERSADDR = "~/Image/"; //封面文件夹路径

    private const string WATERMARK_URL = "~/Images/WaterMark.jpg"; //数字水印路径

    private const string DEFAULT_URL = "~/Images/default.jpg"; //默认图片路径

   

    public void ProcessRequest (HttpContext context) {

        string path = context.Request.MapPath(COVERSADDR + context.Request.Params["ISBN"].ToString() + ".jpg");

        Image Cover;

        if (File.Exists(path))

        {

            Cover = Image.FromFile(path);

            Image watermark = Image.FromFile(context.Request.MapPath(WATERMARK_URL));

            Graphics g = Graphics.FromImage(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_URL));

        }

 

        context.Request.ContentType = "image/ipeg";

        Cover.Save(context.Response.OutputStream,System.Drawing.Imaging.ImageFormat.Jpeg);

        Cover.Dispose();

        context.Response.End();

    }

 

    public bool IsReusable {

        get {

            return false;

        }

    }

 

}

最后在页面或代码中将连接图片的路径都改成

BookCover.ashx?ISBN=数字就可以了

 

在iis要配置一下JPG访问

posted @ 2011-03-02 23:34  双魂人生  阅读(254)  评论(0编辑  收藏  举报