欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-03-11 18:17:25
复制代码 代码如下:using system; using system.data; using system.configuration; using system.we...
复制代码 代码如下:

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>