Watermarks are meant to prevent us from stealing our images.
Two ways to achieve the watermark effect
1) Watermark can be added when the user uploads.
a) Benefits: Compared to the 2 methods, the server sends this image directly to the customer every time the user reads it.
b) Cons: Destroys the original picture.
2) Through the global general processing program, when the user requests this image, add a watermark.
a) Benefits: The original picture is not destroyed
b) Disadvantages: Users need to watermark the requested images every time they make a request, which wastes the server's resources.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Drawing;
- using System.IO;
- namespace Watermark
- {
- /// <summary>
- /// waterH 的摘要说明
- /// </summary>
- public class waterH : IHttpHandler
- {
- public waterH()
- { }
- private const string WATERMARK_URL = "~/Test/watermark.png";
- private const string DEFAULTIMAGE_URL = "~/Test/watermark.png";
- public void ProcessRequest(HttpContext context)
- {
- System.Drawing.Image Cover;
- if (File.Exists(context.Request.PhysicalPath))
- {
- Cover = Image.FromFile(context.Request.PhysicalPath);
- Image watermark = Image.FromFile(context.Request.MapPath(WATERMARK_URL));
- Graphics g = Graphics.FromImage(Cover);
- g.DrawImage(watermark, new Rectangle(Cover.Width - watermark.Width, Cover.Height - watermark.Height, watermark.Width, watermark.Height), 0, 0, watermark.Width, watermark.Height, GraphicsUnit.Pixel);
- g.Dispose();
- watermark.Dispose();
- }
- else
- {
- Cover = Image.FromFile(context.Request.MapPath(DEFAULTIMAGE_URL));
- }
- context.Response.ContentType = "images/jpeg";
- Cover.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
- Cover.Dispose();
- context.Response.End();
- }
- public bool IsReusable
- {
- get
- {
- return false;
- }
- }
- }
- }
Copy code The file code for waterH.ashx is as follows:
Then you need to configure the following node on the web.config:
Under the system.web node
<httpHandlers> <add verb="*" path="Images/*.jpg" type="Watermark.waterH"/> </httpHandlers> At the beginning, the nodes I configured were:
<httpHandlers> <add verb="*" path="Images/*.jpg" type="waterH"/> </httpHandlers> will report an error,
Misconfiguration
Description: An error occurred when processing the profile required to provide services to the request. Please check the specific error details below and modify the configuration file appropriately.
Analyzer error message: Failed to load type "waterH".
Source error:
Line 15: <system.web> Line 16<httpHandlers>: Line 17: <add verb="*" path="Images/*.jpg" type="waterH"/> Line 18: </httpHandlers> Line 19: <compilation debug="true" targetFramework="4.0" />
Finally, inwaterH with the name of the project!
Finally, attach a copy of the source code:
Watermark.rar
(234.64 KB, Number of downloads: 0, 售价: 2 粒MB)
|