前言 |
我们经常在网上下载图片,有很多图片都是有水印的,就搞的很烦。今天分享一个如何给自己上传到自己网址上的图片加上水印。
需求 |
在自己网站上传一张图片,保存在Upload文件夹中并且有自己的水印,只能上传图片,其他的文件上传均无效。
我们可以在前端限制一下上传文件的格式,当然这只能蒙混小菜,大佬可以在网页的开发者工具中把你的限制改掉。我们还要在后端限制一下(毕竟能力有限)。
需求实现 |
前端可以用jquery技术实现
<script>
$(function () {
$(":file").change(function () {
var fileNmae = $(this).val();
var ext = fileNmae.substring(fileNmae.lastIndexOf('.'));
if (ext == ".jpg" || ext == ".png"||ext==".gif") {
return true;
} else {
$(this).val = "";
}
});
});
</script>
后端代码
context.Response.ContentType = "text/html";
//拿到上传来的文件
HttpPostedFile file = context.Request.Files["imgFile"];
if (file == null)
{
context.Response.End();
}
//后台校验
string ext = Path.GetExtension(file.FileName);
if (!(ext == ".jpg" || ext == ".png" || ext == ".gif"))
{
context.Response.Write("格式有误");
}
else
{
string path = "/Upload/" + Guid.NewGuid().ToString() + file.FileName;
file.SaveAs(context.Request.MapPath(path));
string str = string.Format("<html><head></head><body><img src='{0}'/></body></html>", path);
//把图片显示给用户
context.Response.Write(str);
}
添加水印 |
前面我们现实了一个上传图片的功能,当然格式不是就那三个,可以自己在扩展,然后开始添加水印,前端的代码不用变,后端我们用Graphics类下的DrawString方法在我们上传的图片上绘制水印。
context.Response.ContentType = "text/html";
//拿到上传来的文件
HttpPostedFile file = context.Request.Files["imgFile"];
if (file == null)
{
context.Response.End();
}
//把上传的文件做成一个Image对象
Image image = Image.FromStream(file.InputStream);
Graphics graphics = Graphics.FromImage(image);
string str = "版权所有:闫伟强";
graphics.DrawString(str, new Font("黑体", 16), new SolidBrush(Color.Black), new PointF
(image.Width - (25 * str.Length), image.Height - 22));
string strPath = "/Upload/" + Guid.NewGuid().ToString() + file.FileName;
image.Save(context.Request.MapPath(strPath), ImageFormat.Jpeg);
string strHtml = string.Format("<html><head></head><body><img src='{0}'/></body></html>", strPath);
context.Response.Write(strHtml);
效果
总结 |
学习就是一个反复的过程,慢慢积累,既然学过了,就要留下来点!