WaterMarke. cs class code
Using System;
Using System. Data;
Using System. Configuration;
Using System. Web;
Using System. Web. Security;
Using System. Web. UI;
Using System. Web. UI. WebControls;
Using System. Web. UI. WebControls. WebParts;
Using System. Web. UI. HtmlControls;
Using System. Drawing;
Using System. Drawing. Imaging;
Using System. IO;
/// <Summary>
/// Summary of WaterMarker
/// </Summary>
Public class WaterMarker: IHttpHandler
{
Public WaterMarker ()
{
//
// TODO: add the constructor logic here
//
}
Public bool IsReusable
{
Get {return true ;}
}
Public void ProcessRequest (HttpContext context)
{
// Obtain the physical path of the request
String imagePath = context. Request. PhysicalPath;
System. Drawing. Image image = null;
// Determine whether the specified physical path exists
If (File. Exists (imagePath ))
{
// Define watermark text
String text = "this image is from Xia chufeng's blog ";
// Define the watermark text font size
Int fontSize = 12;
// Watermark text font
Font font = new Font ("", fontSize );
// Load the image based on the physical path of the image
Image = System. Drawing. Image. FromFile (imagePath );
Graphics g = Graphics. FromImage (image );
// Obtain the size of the area required to draw the watermark text
SizeF size = g. MeasureString (text, font );
If (size. Width> image. Width | size. Height> image. Height)
{
// Add a watermark based on the specified text font if the size of the image to be displayed is insufficient
// Reduce the font size or add no watermark (too small to add)
}
Else
{
// Add watermark text
Brush br = Brushes. Red;
G. DrawString (text, font, br, image. Width-size. Width, image. Height-size. Height );
G. Dispose ();
}
}
Else // if no default image exists
{
ImagePath = context. Server. MapPath ("~ /Image/default.jpg ");
Image = System. Drawing. Image. FromFile (imagePath );
}
Image. Save (context. Response. OutputStream, ImageFormat. Jpeg); // output the image with the added watermark
}
}
Configuration in webconfig
Method 1: Add a webconfig file in the folder, and then
Add the following code to the <system. web> node:
<HttpHandlers>
<! -- Add a watermark to a jpg file -->
<Add path = "*" verb = "*. jpg" type = "WaterMarker"/>
<! -- Add a watermark to a bmp file -->
<Add verb = "*" path = "*. bmp" type = "WaterMarker"/>
</HttpHandlers>
Method 2: Do not add webconfig in the folder where the image is located, but directly configure webconfig in the root directory.
Instead of Automatically Generating the <System. web> configuration, add the following code to the <configuration> node:
<Location path = "image">
<System. web>
<HttpHandlers>
<! -- Add a watermark to a jpg file -->
<Add path = "*" verb = "*. jpg" type = "WaterMarker"/>
<! -- Add a watermark to a bmp file -->
<Add verb = "*" path = "*. bmp" type = "WaterMarker"/>
</HttpHandlers>
</System. web>
</Location>