asp.net picture add watermark anti-theft Chain Implementation Code _ Practical skills

Source: Internet
Author: User
First build a class:
Copy Code code as follows:

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Web;
Using System.Drawing;
<summary>
Summary description of Class1
</summary>
public class Class1:ihttphandler//Calling interface
{
Public Class1 ()
{
//
TODO: Add 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 ("The Kingdoms", New Font ("Song Body", 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 this site picture");
}
}
}

To register an interface in Web.config:
Copy Code code as follows:


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


Url:http://greatverve.cnblogs.com/archive/2011/12/20/asp-net-hotlinking.html
Reference:
1. Modify Web.config
Copy Code code as follows:

<system.web>

<remove verb= "*" path= "*.asmx"/>
<!--solve the--> of the picture anti-theft chain
<add verb= "*" path= "*.jpg" type= "Myhttphandler.watermark"/>
<add verb= "*" path= "*.gif" type= "Myhttphandler.watermark"/>
<add verb= "*" path= "*.png" type= "Myhttphandler.watermark"/>

</system.web>

2. Add a general execution file watermark.ashx, code as follows:
Copy Code code 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 client buffer time expiration of 0, that is, immediate expiration
Context. Response.Expires = 0;
Empty the server-side output cache opened for this session
Context. Response.Clear ();
To set the output file type
Context. Response.ContentType = "Image/jpg";
Writes 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
{
To add a default watermark configuration
}
DataRow drconfing = dsconfing.tables[0]. Rows[0];
#endregion
String currenthost = drconfing["Allowhost"]. ToString ();
Determine if the local Web site references a picture, and if so, return the correct picture
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 picture
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 ();
}
Writes the request file to the output cache
Imgstart.save (context. Response.outputstream, Imageformat.jpeg);
Imgstart.dispose ();
#endregion
}
Else
{
#region Output Artwork
Writes the request file to the output cache
Context. Response.WriteFile (context. Request.Url.AbsolutePath);
#endregion
}
}
If it is not a local reference, it is hotlinking this site picture
Else
{
Writes the request file to the output cache
Context. Response.WriteFile (context. Request.physicalapplicationpath + drconfing["Errimgpath"]. ToString ());
}
Transferring information from the output cache to the client
Context. Response.End ();
}
<summary>
Position of picture painting watermark
</summary>
<param name= "Positionconfig" > Location type </param>
<param name= "width" > Original picture width </param>
<param name= "Height" ></param>
<param name= "Watermarkwidth" > Watermark 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 Picture 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 Position
</summary>
<param name= "Positionconfig" > Location type </param>
<param name= "width" > Original picture width </param>
<param name= "Height" ></param>
<param name= "Fontwidth" > literal 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 Picture 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 to New Point (xpos, ypos);
}
}
}

3. The watermarkconfig.xml of the configuration file is as follows:
Copy Code code as follows:

<?xml version= "1.0" encoding= "Utf-8"?>
<watermark>
& L t;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-->
<position>bottom-right</position><!--top-left, Top-right , Bottom-left, bottom-right-->
~/UpFiles/Watermark.png</img-path><!--Watermark Location-->
<font-style>1</font-style><!--Plain text 0, bold text 1, italic text 2, underlined text 4, text in the middle with a straight line 8-->
<font-size >60</font-size>
<font-color>red</font-color>
<font-content>¥:8000 yuan </ Font-content>
<errimgpath>images/error.jpg</errimgpath><!--stolen picture request returned with a picture under the directory-->
</watermark>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.