ASP.NET image watermarking anti hotlinking implementation code
- 2020-05-16 06:42:53
- OfStack
First, build a class:
Register the interface in web.config:
url:http://greatverve.cnblogs.com/archive/2011/12/20/asp-net-hotlinking.html
Reference:
1. Modify web. config
2. Add a 1-like execution file Watermark. ashx, the code is as follows:
3. WaterMarkConfig.xml of the configuration file, which reads as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Drawing;
/// <summary>
///Class1 Summary of
/// </summary>
public class Class1:IHttpHandler // Call interface
{
public Class1()
{
//
//TODO: Add the constructor logic here
//
}
public bool IsReusable
{
get { return true; }
}
public void ProcessRequest(HttpContext context)
{
HttpRequest req = context.Request;
if (req.UrlReferrer != null && req.UrlReferrer.Host.Length > 0) // Anti-hotlinking code judgment
{
System.Drawing.Image img = System.Drawing.Image.FromFile(context.Request.PhysicalPath);
System.Drawing.Graphics g = Graphics.FromImage(img);
g.DrawString("3 The historical novel ", new Font(" Song typeface ", 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(" You can not hotlinking site pictures ");
}
}
}
Register the interface in 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
Reference:
1. Modify web. config
<system.web>
<httpHandlers>
<remove verb="*" path="*.asmx"/>
<!-- Solve the problem of image anti-hotlinking -->
<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. Add a 1-like execution file Watermark. ashx, the code is as follows:
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)
{
// Set the client buffer expiration time to 0 , immediately expired
//context.Response.Expires = 0;
// Clear the output cache that was opened on the server side for this session
//context.Response.Clear();
// Sets the output file type
context.Response.ContentType = "image/jpg";
// Writes the request file to the output cache
#region To obtain XML Configuration information
DataSet dsConfing = new DataSet();
string watermarkConfigPath = context.Server.MapPath("~/Config/WaterMarkConfig.xml");
if (System.IO.File.Exists(watermarkConfigPath))
dsConfing.ReadXml(watermarkConfigPath);
else
{
// Add the default watermark configuration
}
DataRow drConfing = dsConfing.Tables[0].Rows[0];
#endregion
string currentHost = drConfing["allowhost"].ToString();
// Determine if the local site is referencing the image, and if so, return the correct image
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 Watermark code
string sImgStartPhysicalPath = context.Request.PhysicalPath;
System.Drawing.Image imgStart = System.Drawing.Image.FromFile(sImgStartPhysicalPath);
// Back up the original image
//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"))
{
// Text watermarking
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();
}
// Writes the request file to the output cache
imgStart.Save(context.Response.OutputStream, ImageFormat.Jpeg);
imgStart.Dispose();
#endregion
}
else
{
#region Output the original image
// Writes the request file to the output cache
context.Response.WriteFile(context.Request.Url.AbsolutePath);
#endregion
}
}
// If it is not a local quote, it is a hotlinking site image
else
{
// Writes the request file to the output cache
context.Response.WriteFile(context.Request.PhysicalApplicationPath + drConfing["errimgpath"].ToString());
}
// The information in the output cache is passed to the client
context.Response.End();
}
/// <summary>
/// The position of watermarks in a picture painting
/// </summary>
/// <param name="positionConfig"> Position type </param>
/// <param name="width"> The original image width </param>
/// <param name="height"></param>
/// <param name="watermarkWidth"> Watermark figure wide </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;// Watermark image scaling
//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>
/// Picture painting text location
/// </summary>
/// <param name="positionConfig"> Position type </param>
/// <param name="width"> The original image width </param>
/// <param name="height"></param>
/// <param name="fontWidth"> Word length </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;// Watermark image scaling
//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 of the configuration file, which reads as follows:
<?xml version="1.0" encoding="utf-8" ?>
<watermark>
<allowhost>localhost:6219</allowhost><!-- Allow access to the domain name -->
<isflag>true</isflag><!-- true , false-->
<type>font</type><!-- img , font-->
<files>/config|/upfiles/ab</files><!-- Folders that need to be watermarked -->
<position>bottom-right</position><!-- top-left , top-right , bottom-left , bottom-right-->
<img-path>~/UpFiles/Watermark.png</img-path><!-- The watermark position -->
<font-style>1</font-style><!-- Plain text 0, Bold text 1, Tilt the text 2, Underlined text 4, Text with a straight line through it 8-->
<font-size>60</font-size>
<font-color>red</font-color>
<font-content> RMB: 8000 yuan </font-content>
<errimgpath>images/error.jpg</errimgpath><!-- The request for stolen images is returned with an image in the directory -->
</watermark>