ASP.NET 图片加水印防盗链实现代码

 更新时间:2021年9月22日 10:19  点击:1415
首先建一个类:
复制代码 代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Drawing;
/// <summary>
///Class1 的摘要说明
/// </summary>
public class Class1:IHttpHandler //调用接口
{
public Class1()
{
//
//TODO: 在此处添加构造函数逻辑
//
}
public bool IsReusable
{
get { return true; }
}
public void ProcessRequest(HttpContext context)
{
HttpRequest req = context.Request;
if (req.UrlReferrer != null && req.UrlReferrer.Host.Length > 0) //反盗链代码判断
{
System.Drawing.Image img = System.Drawing.Image.FromFile(context.Request.PhysicalPath);
System.Drawing.Graphics g = Graphics.FromImage(img);
g.DrawString("三国演义", new Font("宋体", 20, FontStyle.Bold), Brushes.White, 10, 10);
img.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
context.Response.Flush();
context.Response.End();
}
else
{
context.Response.Write("您不能盗链本站图片");
}
}
}

在web.config中注册接口:
复制代码 代码如下:

<httpHandlers>
<add verb="*" path="images/*.jpg" type="Class1,App_Code"/>
</httpHandlers>

url:http://greatverve.cnblogs.com/archive/2011/12/20/asp-net-hotlinking.html
参考:
1.修改web.config
复制代码 代码如下:

<system.web>
<httpHandlers>
<remove verb="*" path="*.asmx"/>
<!--解决图片防盗链问题-->
<add verb="*" path="*.jpg" type="MyHttpHandler.Watermark"/>
<add verb="*" path="*.gif" type="MyHttpHandler.Watermark"/>
<add verb="*" path="*.png" type="MyHttpHandler.Watermark"/>
</httpHandlers>
</system.web>

2.添加一个一般执行文件Watermark.ashx,代码如下:
复制代码 代码如下:

using System;
using System.Data;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Drawing.Imaging;
using System.Drawing;
using System.IO;
namespace MyHttpHandler
{
/// <summary>
/// Summary description for $codebehindclassname$
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Watermark : IHttpHandler
{
public bool IsReusable
{
get
{
return false;
}
}
public void ProcessRequest(HttpContext context)
{
//设置客户端缓冲时间过期时间为0,即立即过期
//context.Response.Expires = 0;
//清空服务器端为此会话开启的输出缓存
//context.Response.Clear();
//设置输出文件类型
context.Response.ContentType = "image/jpg";
//将请求文件写入到输出缓存中
#region 获取XML配置信息
DataSet dsConfing = new DataSet();
string watermarkConfigPath = context.Server.MapPath("~/Config/WaterMarkConfig.xml");
if (System.IO.File.Exists(watermarkConfigPath))
dsConfing.ReadXml(watermarkConfigPath);
else
{
//添加默认的水印配置
}
DataRow drConfing = dsConfing.Tables[0].Rows[0];
#endregion
string currentHost = drConfing["allowhost"].ToString();
//判断是否是本地网站引用图片,如果是则返回正确的图片
if (context.Request.Url.Authority.Equals(currentHost, StringComparison.InvariantCultureIgnoreCase))
{
string localPath = context.Request.Url.LocalPath;
localPath = localPath.Remove(localPath.LastIndexOf('/')).ToLower();// "/images/userphoto"
if (drConfing["isflag"].Equals("true") && drConfing["files"].ToString().ToLower().IndexOf(localPath) > 0)
{
#region 水印代码
string sImgStartPhysicalPath = context.Request.PhysicalPath;
System.Drawing.Image imgStart = System.Drawing.Image.FromFile(sImgStartPhysicalPath);
//备份原图片
//int indexOf = sImgStartPhysicalPath.LastIndexOf(".");
//string bakPath = sImgStartPhysicalPath.Remove(indexOf) + "_bak" + sImgStartPhysicalPath.Substring(indexOf);
//imgStart.Save(bakPath);
Graphics gh = System.Drawing.Graphics.FromImage(imgStart);
if (drConfing["type"].Equals("img"))
{
System.Drawing.Image imgWatermark = System.Drawing.Image.FromFile(context.Server.MapPath(drConfing["img-path"].ToString()));
Rectangle rg = SetImgPosition(drConfing["position"].ToString(), imgStart.Width, imgStart.Height, imgWatermark.Width, imgWatermark.Height);
gh.DrawImage(imgWatermark, rg, 0, 0, imgWatermark.Width, imgWatermark.Height, GraphicsUnit.Pixel);
gh.Save();
gh.Dispose();
imgWatermark.Dispose();
}
else if (drConfing["type"].Equals("font"))
{
//文字水印
string content = drConfing["font-content"].ToString();
float Size = (float)Convert.ToDouble(drConfing["font-size"].ToString());
FontStyle fontStyle = (FontStyle)int.Parse(drConfing["font-style"].ToString());
System.Drawing.Font f = new System.Drawing.Font("Arial", Size, fontStyle);
Color G_Color = Color.FromName(drConfing["font-color"].ToString());
System.Drawing.Brush b = new System.Drawing.SolidBrush(G_Color);
SizeF sizeF = gh.MeasureString(content, f);
gh.DrawString(content, f, b, SetFontPosition(drConfing["position"].ToString(), imgStart.Width, imgStart.Height, (int)sizeF.Width, (int)sizeF.Height));
gh.Save();
gh.Dispose();
}
//将请求文件写入到输出缓存中
imgStart.Save(context.Response.OutputStream, ImageFormat.Jpeg);
imgStart.Dispose();
#endregion
}
else
{
#region 输出原图
//将请求文件写入到输出缓存中
context.Response.WriteFile(context.Request.Url.AbsolutePath);
#endregion
}
}
//如果不是本地引用,则是盗链本站图片
else
{
//将请求文件写入到输出缓存中
context.Response.WriteFile(context.Request.PhysicalApplicationPath + drConfing["errimgpath"].ToString());
}
//将输出缓存中的信息传送到客户端
context.Response.End();
}
/// <summary>
/// 图片绘画水印的位置
/// </summary>
/// <param name="positionConfig">位置类型</param>
/// <param name="width">原图片宽</param>
/// <param name="height"></param>
/// <param name="watermarkWidth">水印图宽</param>
/// <param name="watermarkHeight"></param>
/// <returns></returns>
private Rectangle SetImgPosition(string positionConfig,int width,int height,int watermarkWidth,int watermarkHeight)
{
int xpos = 0;
int ypos = 0;
int margin = 10;
int width_margin = width - margin;
int height_margin = height - margin;
double proportion = 1d;//水印图片缩放比例
//int
if ((width_margin > watermarkWidth * proportion) && (height_margin > watermarkHeight * proportion))
{
}
else if ((width_margin > watermarkWidth * proportion) && (height_margin < watermarkHeight * proportion))
{
proportion = Convert.ToDouble( height_margin) / Convert.ToDouble( watermarkHeight);
}
else if ((width_margin < watermarkWidth * proportion) && (height_margin > watermarkHeight * proportion))
{
proportion = Convert.ToDouble(width_margin) / Convert.ToDouble(watermarkWidth);
}
else
{
double proportionW = Convert.ToDouble(width_margin) / Convert.ToDouble(watermarkWidth);
double proportionH = Convert.ToDouble(height_margin) / Convert.ToDouble(watermarkHeight);
proportion = proportionW >= proportionH ? proportionH : proportionW;
}
watermarkWidth = Convert.ToInt32(watermarkWidth * proportion);
watermarkHeight = Convert.ToInt32(watermarkHeight * proportion);
switch (positionConfig)
{
case "top-left":
xpos = margin;
ypos = margin;
break;
case "top-right":
xpos = width_margin - watermarkWidth;
ypos = margin;
break;
case "bottom-left":
xpos = margin;
ypos = height_margin - watermarkHeight;
break;
case "bottom-right":
xpos = width_margin - watermarkWidth ;
ypos = height_margin - watermarkHeight ;
break;
default:
xpos = width_margin - watermarkWidth ;
ypos = height_margin - watermarkHeight;
break;
}
return new Rectangle(xpos,ypos,watermarkWidth,watermarkHeight);
}
/// <summary>
/// 图片绘画文字位置
/// </summary>
/// <param name="positionConfig">位置类型</param>
/// <param name="width">原图片宽</param>
/// <param name="height"></param>
/// <param name="fontWidth">文字长度</param>
/// <param name="fontHeight"></param>
/// <returns></returns>
private Point SetFontPosition(string positionConfig, int width, int height, int fontWidth, int fontHeight)
{
int xpos = 0;
int ypos = 0;
int margin = 10;
int width_margin = width - margin;
int height_margin = height - margin;
double proportion = 1d;//水印图片缩放比例
//int
if ((width_margin > fontWidth * proportion) && (height_margin > fontHeight * proportion))
{
}
else if ((width_margin > fontWidth * proportion) && (height_margin < fontHeight * proportion))
{
proportion = Convert.ToDouble(height_margin) / Convert.ToDouble(fontHeight);
}
else if ((width_margin < fontWidth * proportion) && (height_margin > fontHeight * proportion))
{
proportion = Convert.ToDouble(width_margin) / Convert.ToDouble(fontWidth);
}
else
{
double proportionH = Convert.ToDouble(height_margin) / Convert.ToDouble(fontHeight);
double proportionW = Convert.ToDouble(width_margin) / Convert.ToDouble(fontWidth);
proportion = proportionW >= proportionH ? proportionH : proportionW;
}
fontWidth = Convert.ToInt32(fontWidth * proportion);
fontHeight = Convert.ToInt32(fontHeight * proportion);
switch (positionConfig)
{
case "top-left":
xpos = margin;
ypos = margin;
break;
case "top-right":
xpos = width_margin - fontWidth;
ypos = margin;
break;
case "bottom-left":
xpos = margin;
ypos = height_margin - fontHeight;
break;
case "bottom-right":
xpos = width_margin - fontWidth;
ypos = height_margin - fontHeight;
break;
default:
xpos = width_margin - fontWidth;
ypos = height_margin - fontHeight;
break;
}
return new Point(xpos, ypos);
}
}
}

3.配置文件的WaterMarkConfig.xml,内容如下:
复制代码 代码如下:

<?xml version="1.0" encoding="utf-8" ?>
<watermark>
<allowhost>localhost:6219</allowhost><!--允许访问的域名-->
<isflag>true</isflag><!-- true、false-->
<type>font</type><!-- img、font-->
<files>/config|/upfiles/ab</files><!--需要加水印的文件夹-->
<position>bottom-right</position><!-- top-left、top-right、bottom-left、bottom-right-->
<img-path>~/UpFiles/Watermark.png</img-path><!-- 水印位置 -->
<font-style>1</font-style><!--普通文本 0, 加粗文本 1, 倾斜文本 2, 带下划线的文本 4, 中间有直线通过的文本 8-->
<font-size>60</font-size>
<font-color>red</font-color>
<font-content>¥:8000元</font-content>
<errimgpath>images/error.jpg</errimgpath><!-- 盗图片的请求返回的跟目录下的某图片 -->
</watermark>
[!--infotagslink--]

相关文章

  • apache 防盗链配置方法

    修改httpd.conf 找到 <Dirctory "/var/www/html"> 在这个Dirctory容器内添加: 代码如下 复制代码 SetEnvIfNoCase Referer "^http://www.111cn.net/"...2016-01-28
  • python实现图片加文字水印OPenCV和PIL库

    本文来为大家介绍一下,使用python中的库实现给图片添加文字水印,openCV可以给图片添加水印,如果要添加汉字水印那就要使用PIL库...2021-09-26
  • Linux中Nginx的防盗链和优化的实现代码

    今天是周末小编在值班哈,很开森,工作使我快乐,本文重点给大家介绍Linux中Nginx的防盗链和优化问题及实现代码,需要的朋友跟随小编一起看看吧...2021-06-19
  • 真正可用的IIS的ISAPI-Rewrite伪静态URL图片防盗链规则写法

    本规则支持白名单排除式防盗链,搜索引擎友好不屏蔽,被盗链后的错误提示转向,支持各种文件类型,经作者亲验真的能用...2016-01-27
  • PHP:实现给上传图片加水印的程序代码

    用PHP给上传图片加水印的程序是通过判定文件类型建立图形,然后把其复制到原建立的图形上,填充并建立rectangle,以备写入imagestring()或是原已经定好的图像程序当中判定水...2016-11-25
  • php图片上传类,支持加水印,生成略缩图

    分享一个网友写的php图片上传类,支持加水印,生成略缩图功能哦,面是配置和可以获取的一些信息(每一个配置信息都有默认值,如无特殊需要,可以不配置): 代码如下 ...2016-11-25
  • 一个给图片加水印的程序

    尚未测试 CODE: <?php /****************************************************************************** 参数说明: $max_file_size : 上传文件大小限制, 单位BY...2016-11-25
  • php 图片上传加水印(自动增加水印)

    这是一款完美的php文件上传代码,图片上传成功后并自动给图片增加上水印,这样很好的快速的提高的了要手工一张张增加水印效果。 代码如下 复制代码 ...2016-11-25
  • php简单防盗链验证实现方法 原创

    这篇文章主要介绍了php简单防盗链验证实现方法,通过$_SERVER['HTTP_REFERER']获取来路页面URL再进行判断进而实现对非本地URL的拦截功能,需要的朋友可以参考下...2016-07-25
  • PHP imagecopy()与imagecopymerge()图像添加水印

    图像添加水印在php中有很多种办法可以实现,他这些功能都是基于php中的GD库的,如果没有开户GD库是不可以使用水印功能的。 imagecopymerge() 函数用于拷贝并合并图像...2016-11-25
  • nginx rewrite重写规则与防盗链配置方法教程详解

    这篇文章主要介绍了nginx rewrite重写规则与防盗链配置方法教程详解,非常不错,具有参考借鉴价值,需要的朋友可以参考下...2016-09-28
  • Asp.net 图片文件防盗链(尊重劳动成果)及BeginRequest事件学习

    关于图片盗链这个问题,毕竟是自己的劳动成功,很多人不希望别人就那么轻易地偷走了;反盗链的程序其实很简单,熟悉ASP.NET 应用程序生命周期的话很容易就可以写一个,运用HttpModule在BeginRequest事件中拦截请求就ok了...2021-09-22
  • php破解apache,nginx,iis防盗链图片

    现在多数网站都有防盗链一些简单设置了最常用的就是apache,nginx,iis设置了,那么这种设置是不是不可破的呢,答案是否写了,下面我们一起来看破解方法。 有自己的主机...2016-11-25
  • 用rewrite实现IIS下图片文件防盗链的办法

    IIS不支持UrlRewrite。 所以我们需要通过安装第三方服务器扩展让IIS支持UrlRewrite。 目前有一种产品能比较好地支持IIS的UrlRewrite,名字叫ISAPI_Rewrite。...2016-01-27
  • php新浪云平台给图片添加水印方法

    本文章来为各位介绍一篇关于php新浪云平台给图片添加水印方法的例子,希望这篇教程能够帮助到各位使用新浪云平台的朋友. <?php //原文件名 $file_name = $_FILES[...2016-11-25
  • php 多个文件上传(给图片加水印实例)

    代码如下 复制代码 <!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.d...2016-11-25
  • apache设置防盗链有效方法

    代码如下 复制代码 <VirtualHost *:80> DocumentRoot d:/soft/soft ServerName 111cn.net SetEnvIfNoCase Referer "^http://www.111cn.net...2016-01-28
  • C#给Excel添加水印实例详解

    这篇文章主要介绍了C#给Excel添加水印实例的相关资料,需要的朋友可以参考下...2020-06-25
  • php使用imagick给图片加水印的方法

    下面我们来看一篇关于php使用imagick给图片加水印的方法吧,希望这篇文章能够让各位了解到imagick图片加水印的个方法方式。 <?php $image = new Imagick(); $ima...2016-11-25
  • IIS图片防盗链和下载的解决方案

    最近服务器需要防图片别盗链,所以找了很多代码,下面给出具体配置代码...2016-01-27