1. 程式人生 > 程式設計 >ASP.NET實現圖片自動新增水印

ASP.NET實現圖片自動新增水印

本文例項為大家分享了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,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();


  }
 }
}

修改配置檔案

ASP.NET實現圖片自動新增水印

<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>

效果圖

ASP.NET實現圖片自動新增水印

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。