本文实例为大家分享了asp.net实现图片自动添加水印的具体代码,供大家参考,具体内容如下

先建一个类,感觉注释已经很详细了,有不懂的欢迎评论

using system;
using system.collections.generic;
using system.drawing;
using system.drawing.imaging;
using system.io;
using system.linq;
using system.web;

namespace shuiyin
{
 public class water : ihttphandler
 {
  /*
   这个isreusable的true是可以提高效率但是,会线程不安全
   ihttphandler实例可以再次使用

   false,会安全一些,效率会低一些
   ihttphandler的实例就不能使用 
    */
  public bool isreusable => true;
  //水印
  private const string water_url = "~/images/watermark.png";
  //没有图片的时候使用
  private const string none_picture = "~/error/default.jpg";

  public void processrequest(httpcontext context)
  {
   //获取图片的物理路径
   string path = context.request.physicalpath;
   image image;
   //如果我当前项目中有这个图片,就可以进行加水印操作
   if (file.exists(path))
   {
    //获取指定的图片(要添加水印的图片)
    image = image.fromfile(path);
    //再找到,要添加的水印
    image image_water = image.fromfile(context.server.mappath(water_url));
    //使用画图的类,获取图片
    graphics graphics = graphics.fromimage(image);
    //画图方法,第一个参数就是要添加的水印
    graphics.drawimage(image_water,
     //第二个参数是一个坐标的问题,从x1,y1坐标开始,绘制的水印的长度和宽度,
     //一共四个参数,x1,y1,水印的长度,宽度
     new rectangle(image.width - image_water.width, image.height - image_water.height, image_water.width, image_water.height),
     //从上一个参数获取的位置开始作为新的区域
     //新区域的0,0开始,也是宽度和长度,
     //最后一个参数就是,像素的问题,多少像素
     0, 0, image_water.width, image_water.height,graphicsunit.pixel);
    //使用完了,把两个图片的资源都释放掉
    graphics.dispose();
    image_water.dispose();
   }
   else
   {
    //这里是如果没有指定的图片的话,就用一个找不到的图片去代替
    image = image.fromfile(context.server.mappath(none_picture));
   }
   //新图片的类型
   context.response.contenttype = "image/jpeg";
   //把新图片进行保存,输出流和格式
   image.save(context.response.outputstream, imageformat.jpeg);
   //使用完保存,释放掉图片的资源,结束
   image.dispose();
   context.response.end();


  }
 }
}

修改配置文件

<system.webserver>
 <handlers>
  <add verb="*" name="image_water" path="images/*.jpg" type="shuiyin.water"/>
 </handlers>
</system.webserver>

path是加水印图片的地址,type是那个类的路径:
也就是命名空间 .(点)类名

一个简单的web窗体

<%@ page language="c#" autoeventwireup="true" codebehind="threepicture_water.aspx.cs" inherits="shuiyin.threepicture_water" %>

<!doctype html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
 <title></title>
</head>
<body>
 <form id="form1" runat="server">
  <div>
   <img src="images/adv1.jpg" />
   <img src="images/adv2.jpg" />
   <img src="images/adv3.jpg" />
  </div>
 </form>
</body>
</html>

效果图

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持www.887551.com。