The effect of adding watermarks to images is a feature that almost all programmers must use. I will share a very good program code for adding watermarks to lossless images in asp.net. I hope this will be helpful to everyone.
Watermarks are used to prevent image theft.
Two ways to achieve the watermark Effect
1) You can add a watermark when uploading a file.
A) Benefits: Compared with the two methods, each time a user reads the image, the server sends it directly to the customer.
B) Disadvantage: the original image is damaged.
2) use a general global processing program to add a watermark when the user requests this image.
A) benefits: the original image is not damaged.
B) Disadvantages: users need to add watermarks to the requested images each time they request them, wasting server resources.
The second method of code implementation:
The Code is as follows:
The Code is as follows: |
Copy code |
Using System; Using System. Collections. Generic; Using System. Linq; Using System. Web; Using System. Drawing; Using System. IO; Namespace BookShop. Web { Public class WaterMark: IHttpHandler { Private const string WATERMARK_URL = "~ /Images/watermark.jpg "; // watermark image Private const string DEFAULTIMAGE_URL = "~ /Images/default.jpg "; <span style =" white-space: pre "> </span> // default image # Region IHttpHandler Member Public bool IsReusable { Get {return false ;} } Public void ProcessRequest (HttpContext context) { // Context. Request. PhysicalPath // obtain the physical path of the file requested by the user System. Drawing. Image Cover; // Determine whether a file exists in the request's physical path If (File. Exists (context. Request. PhysicalPath )) { // Load the file Cover = Image. FromFile (context. Request. PhysicalPath ); // Load the watermark image Image watermark = Image. FromFile (context. Request. MapPath (WATERMARK_URL )); // Use the cover of the book to obtain the Drawing Object Graphics g = Graphics. FromImage (Cover ); // Draw a watermark on the image G. DrawImage (watermark, new Rectangle (Cover. Width-watermark. Width, Cover. Height-watermark. Height, |
The Code is as follows:
The Code is as follows: |
Copy code |
Watermark. Width, watermark. Height), 0, 0, watermark. Width, watermark. Height, GraphicsUnit. Pixel ); // Release the canvas G. Dispose (); // Release the watermark image Watermark. Dispose (); } Else { // Load the default image Cover = Image. FromFile (context. Request. MapPath (DEFAULTIMAGE_URL )); } // Set the output format Context. Response. ContentType = "image/jpeg "; // Save the image to the output stream Cover. Save (context. Response. OutputStream, System. Drawing. Imaging. ImageFormat. Jpeg ); Cover. Dispose (); Context. Response. End (); } # Endregion } } |