asp.net如何给每张图片动态添加水印方法(二)

第一步,在App_Code中新建一个类,类名为BookCoverHandler,然后代码如下

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Drawing;

using System.Drawing.Imaging;

using System.IO;


/// <summary>

///BookCoverHandler 的摘要说明

/// </summary>

public class BookCoverHandler:IHttpHandler

{

    public void ProcessRequest(HttpContext context)

    {

        //获取请求的图片信息

        //string isbn = context.Request.QueryString["isbn"];


        //找图片

        //string path = context.Server.MapPath("~/Images/BookCovers/" + isbn + ".jpg");

        string path = context.Request.PhysicalPath;

        string defaultPath = context.Server.MapPath("~/images/default.jpg");

        string waterPath = context.Server.MapPath("~/images/watermark.jpg");

        //处理图片

        Image cover;

        //图片存在加水印

        if (File.Exists(path))

        {

            Image water = Image.FromFile(waterPath);

            cover = Image.FromFile(path);

            Graphics g = Graphics.FromImage(cover);

            g.DrawImage(water,

                cover.Width - water.Width,

                cover.Height - water.Height,

                water.Width,

                water.Height);

            g.Dispose();

        }

        else//图片不存在加载默认图片 

        {

            cover = Image.FromFile(defaultPath);

        }

        context.Response.ContentType = "image/jpeg";

        cover.Save(context.Response.OutputStream, ImageFormat.Jpeg);

        cover.Dispose();

        context.Response.End();

    }


    public bool IsReusable

    {

        get

        {

            return true;

        }

    }

}

第二部,在web.config中

    <httpHandlers>

      <!--图片水印-->

      <add verb="*" type="BookCoverHandler" path="Images/BookCovers/*.jpg" />

    </httpHandlers>

然后就会为Images/BookCovers/下的jpg图片自动添加水印


转载于:https://www.cnblogs.com/zhanghai/p/4461255.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值