给图片加水印,是多数网站做的简洁明了的版权说明
做一个模拟版的
目前学了两种给图片加水印的方案,做个学习记录
通过一般处理程序(.ashx)
将文件名称传到一般处理程序中
前端页面,在此指定图片路径
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="给图片加水印.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Image ID="Image1" runat="server" ImageUrl="文件路经" />
</div>
</form>
</body>
</html>
通过后台传递图片名称
//获取图片(通过切割字符串,找出文件的名称)
string imgname = Image1.ImageUrl.Split('/')[Image1.ImageUrl.Split('/').Length - 1];
//将文件名称传给一般处理程序
Image1.ImageUrl = "Handler1.ashx?img=" + imgname;
在一般处理程序中对文件进行处理,将结果返回前端页面
此方案有一定的局限性
原理是将指定的图片当作画布,在其上使用画笔工具在指定的位置画出想要的文字
画笔方位,一左上角为原点
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Web;
namespace 给图片加水印
{
public class Handler1 : IHttpHandler
{
//服务器存放图片的路径 只能用‘~’不能用‘..’
public static string img_url = "~/images/";
//如果去请求不到图片 那么给张默认图片
public static string Def_img = "~/images/def.png";
public void ProcessRequest(HttpContext context)
{
string imgname = context.Request.QueryString["img"].ToString();
//存放图片的路径 加上图片的名称 就是真正的路径(虚拟路径)
string imgpath = img_url + imgname;
//将虚拟路径 转换成物理路径
string wlpath = context.Request.MapPath(imgpath);
Image tp;
//物理路径释放存在该图片
if (File.Exists(wlpath))
{
//加载图片
tp = Image.FromFile(wlpath);
//实例化画布对象
Graphics grap = Graphics.FromImage(tp);
//创建字体对象
Font font = new Font("微软雅黑", 16);//(字体样式,字体大小-->像素)
grap.DrawString("新鲜美淘网", font, Brushes.Red, tp.Width - 120, tp.Height - font.Height);
//释放画布
grap.Dispose();
}
else
{
tp = Image.FromFile(context.Request.MapPath(Def_img));
}
//设置输出格式
context.Response.ContentType = "image/png";
//将图片存入输出流
tp.Save(context.Response.OutputStream, ImageFormat.Png);
//释放图片
tp.Dispose();
//停止http的响应
context.Response.End();
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
分享至此,下篇文章更新上传时加水印,采用另为一种方案