当前位置: 移动技术网 > IT编程>开发语言>.net > C# 给站点指定位置的某种格式的图片添加水印

C# 给站点指定位置的某种格式的图片添加水印

2017年12月12日  | 移动技术网IT编程  | 我要评论

百日红,贺州580,创意中国

复制代码 代码如下:

using system;
using system.data;
using system.configuration;
using system.web;
using system.web.security;
using system.web.ui;
using system.web.ui.webcontrols;
using system.web.ui.webcontrols.webparts;
using system.web.ui.htmlcontrols;
using system.drawing;
namespace chen
{
/// <summary>
/// handlerimageopener 的摘要说明
/// </summary>
public class handlerimageopener : ihttphandler
{
public handlerimageopener()
{
//
// todo: 在此处添加构造函数逻辑
//
}
private string _path = "";
/// <summary>
/// 水印图片路径
/// </summary>
public string pngpath
{
get
{
if (_path == "")
{
_path = system.web.httpcontext.current.server.mappath(configurationmanager.appsettings["watermarkedimagepath"]);
}
return _path;
}
}
/// <summary>
/// 为图片加水印并写入到response.outputstream
/// </summary>
/// <param name="hc">上下文对象</param>
public void getnewbitmap(httpcontext hc)
{
// 加载原图片
//system.web.httpcontext.current.response.write(system.drawing.image.fromfile(hc.request.physicalpath));
//system.web.httpcontext.current.response.end();
bitmap oldbmp = new bitmap(system.drawing.image.fromfile(hc.request.physicalpath));
int newwidth = oldbmp.width;
int newheight = oldbmp.height;
if (oldbmp != null)
{
// 绑定画板
graphics grap = graphics.fromimage(oldbmp);
// 加载水印图片
bitmap bt = new bitmap(pngpath);
// 水印位置控制
int ph = getnewpoint(newheight, bt.height, true);
int pw = getnewpoint(newwidth, bt.width, false);
if (newheight < ph * 8)
ph = ph / 2;
if (newwidth < pw)
pw = pw / 2 / 2;
int px = newheight - ph;
int py = newwidth - pw - 3;
// 添加水印
grap.drawimage(bt, py, px, pw, ph);
// 写入到输出流
oldbmp.save(hc.response.outputstream, system.drawing.imaging.imageformat.jpeg);
}
}
// 控制宽高
private int getnewpoint(int oldp, int newp, bool isw)
{
int p = 4;
if (isw)
{
p = 16;
}
if (oldp < (newp * p))
{
newp /= 2;
if (oldp < (newp * p))
{
getnewpoint(oldp, newp, isw);
}
}
return newp;
}
#region ihttphandler 成员
bool ihttphandler.isreusable
{
get { return true; }
}
void ihttphandler.processrequest(httpcontext context)
{
getnewbitmap(context);
}
#endregion
}
}
生成.dll文件后在web.config 中配置
<!--水印图片路径-->
<appsettings>
<add key="watermarkedimagepath" value="~/logo.gif"/>
</appsettings>
<!--引用处理函数 path为需要加水印图片的目录-->
<httphandlers>
<add type="chen.handlerimageopener, chen" verb="*" path="image/*.jpg,image/*.gif,image/*.png,image/*.bmp" />
</httphandlers>

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网