First, create a class:
Copy codeThe Code is as follows:
Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Web;
Using System. Drawing;
/// <Summary>
/// Summary of Class1
/// </Summary>
Public class Class1: IHttpHandler // call the 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-leeching code judgment
{
System. Drawing. Image img = System. Drawing. Image. FromFile (context. Request. PhysicalPath );
System. Drawing. Graphics g = Graphics. FromImage (img );
G. DrawString ("Romance of the Three Kingdoms", 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 ("you cannot steal images on this site ");
}
}
}
Register the interface in web. config:
Copy codeThe Code is as follows:
<HttpHandlers>
<Add verb = "*" path = "images/*. jpg" type = "Class1, App_Code"/>
</HttpHandlers>
Url: http://greatverve.cnblogs.com/archive/2011/12/20/asp-net-hotlinking.html
Refer:
1. modify web. config
Copy codeThe Code is as follows:
<System. web>
<HttpHandlers>
<Remove verb = "*" path = "*. asmx"/>
<! -- Solve the problem of image anti-leech -->
<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 general execution file Watermark. ashx. The Code is as follows:
Copy codeThe 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, that is, immediate expiration
// Context. Response. Expires = 0;
// Clear the output cache enabled by the server for this session
// Context. Response. Clear ();
// Set the output file type
Context. Response. ContentType = "image/jpg ";
// Write the request file to the output Cache
# Region get 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 whether the image is referenced by a local website. If yes, the correct image is returned.
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 watermark
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 ();
}
// Write the request file to the output Cache
ImgStart. Save (context. Response. OutputStream, ImageFormat. Jpeg );
ImgStart. Dispose ();
# Endregion
}
Else
{
# Region output source Image
// Write the request file to the output Cache
Context. Response. WriteFile (context. Request. Url. AbsolutePath );
# Endregion
}
}
// If it is not a local reference, it is the image of the leeching site
Else
{
// Write the request file to the output Cache
Context. Response. WriteFile (context. Request. PhysicalApplicationPath + drConfing ["errimgpath"]. ToString ());
}
// Send the information in the output cache to the client
Context. Response. End ();
}
/// <Summary>
/// Position of the Image Watermark
/// </Summary>
/// <Param name = "positionConfig"> location type </param>
/// <Param name = "width"> original image width </param>
/// <Param name = "height"> </param>
/// <Param name = "watermarkWidth"> watermark image width </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 ratio
// 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>
/// Position of the image painting text
/// </Summary>
/// <Param name = "positionConfig"> location type </param>
/// <Param name = "width"> original image width </param>
/// <Param name = "height"> </param>
/// <Param name = "fontWidth"> text 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 ratio
// 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. The WaterMarkConfig. xml file contains the following content:
Copy codeThe Code is as follows:
<? Xml version = "1.0" encoding = "UTF-8"?>
<Watermark>
& Lt; allowhost & gt; localhost: 6219 & lt;/allowhost & gt; & lt! -- Allowed domain name -->
<Isflag> true </isflag> <! -- True, false -->
<Type> font </type> <! -- Img, font -->
<Files>/config |/upfiles/AB </files> <! -- The folder to be watermarked -->
<Position> bottom-right </position> <! -- Top-left, top-right, bottom-left, and bottom-right -->
~ /UpFiles/Watermark.png </img-path> <! -- Watermark position -->
<Font-style> 1 </font-style> <! -- Plain text 0, bold text 1, skewed text 2, underlined text 4, text 8 with a straight line in the middle -->
<Font-size> 60 </font-size>
<Font-color> red </font-color>
<Font-content> ¥: 8000 RMB </font-content>
<Errimgpath> images/error.jpg </errimgpath> <! -- An image in the same directory returned by the image stealing request -->
</Watermark>