How to realize watermarking in asp.net
This article is about how to implement watermark in asp.net. Xiaobian thinks it is quite practical, so share it with everyone for reference. Let's follow Xiaobian and have a look.
Two ways to achieve watermark effect
1)Watermarks can be added when users upload.
a) Benefits: Compared to the two methods, each time the user reads this image, the server sends it directly to the client.
b) Disadvantages: Destroy the original image.
2)Through global general processing, when the user requests this image, watermark it.
a) Benefits: The original image is not corrupted
b) Disadvantages: users need to watermark the requested image every time they request, wasting server resources.
The code is implemented in the second way:
The code is as follows:
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"; //default image
#region IHttpHandler member
public bool IsReusable
{
get { return false; }
}
public void ProcessRequest(HttpContext context)
{
//context.Request.PhysicalPath the physical path to the file requested by the user
System.Drawing.Image Cover;
//Determine whether there is a file in the physical path of the request
if (File.Exists(context.Request.PhysicalPath))
{
//load file
Cover = Image.FromFile(context.Request.PhysicalPath);
//load watermark image
Image watermark = Image.FromFile(context.Request.MapPath(WATERMARK_URL));
//Get drawing object through book cover
Graphics g = Graphics.FromImage(Cover);
//Draw watermark on image
g.DrawImage(watermark, new Rectangle(Cover.Width - watermark.Width, Cover.Height - watermark.Height,
[csharp] view plaincopy
watermark.Width, watermark.Height), 0, 0, watermark.Width, watermark.Height, GraphicsUnit.Pixel);
//Release canvas
g.Dispose();
//release watermark image
watermark.Dispose();
}
else
{
//load default image
Cover = Image.FromFile(context.Request.MapPath(DEFAULTIMAGE_URL));
}
//Set output format
context.Response.ContentType = "image/jpeg";
//save images to output stream
Cover.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
Cover.Dispose();
context.Response.End();
}
#endregion
}
}
Thank you for reading! About "how to achieve watermark in ASP.NET" this article is shared here, I hope the above content can be of some help to everyone, so that everyone can learn more knowledge, if you think the article is good, you can share it to let more people see it!