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="*" 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 runat="server"> <div> <img src="http://www.jb51.net/article/Images/adv1.jpg" /> <img src="http://www.jb51.net/article/Images/adv2.jpg" /> <img src="http://www.jb51.net/article/Images/adv3.jpg" /> </div> </form> </body> </html> 结果图
(编辑:湖南网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |