图片添加水印
1.创建web项目并添加窗体,然后新建文件夹
如下图所示:
如有不懂请看下面这个链接:
https://blog.csdn.net/m0_49928665/article/details/117427002
窗体代码如下:
<body>
<form id="form1" runat="server">
<div>
<img src="Images/1.jpg" />
<img src="Images/2.jpg" />
<img src="Images/3.jpg" />
</div>
</form>
</body>
添加TestHandler类
代码如下:
public class TestHandler : IHttpHandler
{
//水印图片
private const string WATERMARK_URL = "~/Images/watermark.png";
//图片不存在,默认下显示图片
private const string DEFAULTIMAGE_URL = "~/Images/1.jpg";
public bool IsReusable
{
get { return false; }
}
public void ProcessRequest(HttpContext context)
{
//得到用户请求的图片
string filePath = context.Request.PhysicalPath;
System.Drawing.Image Cover;
//判断请求的路径是否存在文件
if (File.Exists(filePath))
{
//加载文件
Cover = Image.FromFile(filePath);
//加载水印图片
Image wateremark = Image.FromFile(context.Server.MapPath(WATERMARK_URL));
//实例化画布
Graphics g = Graphics.FromImage(Cover);
//在image上绘制水印
g.DrawImage(wateremark, new Rectangle(Cover.Width - wateremark.Width,
Cover.Height - wateremark.Height, wateremark.Width, wateremark.Height), 0,
0, wateremark.Width, wateremark.Height, GraphicsUnit.Pixel);
//释放画布
g.Dispose();
//释放水印图片
wateremark.Dispose();
}
else
{
//加载默认图片
Cover = Image.FromFile(context.Request.MapPath(DEFAULTIMAGE_URL));
}
//设置输出格式
context.Response.ContentType = "image/jpeg";
//将图片存入输出流
Cover.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
Cover.Dispose();
context.Response.End();
}
在web.config里插入代码
代码如下:
<handlers>
<add verb="*" path="Images/*.jpg" name="handler" type="_5._4.TestHandler"/>
</handlers>