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

C# 添加文字水印类代码

程序员文章站 2024-03-09 12:39:11
复制代码 代码如下:using system; using system.collections.generic; using system.text; using sys...
复制代码 代码如下:

using system;
using system.collections.generic;
using system.text;
using system.drawing;
using system.io;
using system.drawing.imaging;
namespace chen
{
public class warterfont
{
public void addtexttoimg(string filename, string text)
{
if (!file.exists(system.web.httpcontext.current.server.mappath(filename)))
{
throw new filenotfoundexception("the file don't exist!");
}
if (text == string.empty)
{
return;
}
//还需要判断文件类型是否为图像类型,这里就不赘述了
image image = image.fromfile(system.web.httpcontext.current.server.mappath(filename));
bitmap bitmap = new bitmap(image, image.width, image.height);
graphics g = graphics.fromimage(bitmap);
float fontsize = 12.0f; //字体大小
float textwidth = text.length * fontsize; //文本的长度
//下面定义一个矩形区域,以后在这个矩形里画上白底黑字
float rectx = 0;
float recty = 0;
float rectwidth = text.length * (fontsize + 8);
float rectheight = fontsize + 8; //声明矩形域
rectanglef textarea = new rectanglef(rectx, recty, rectwidth, rectheight);
font font = new font("宋体", fontsize); //定义字体
brush whitebrush = new solidbrush(color.white); //白笔刷,画文字用
brush blackbrush = new solidbrush(color.black); //黑笔刷,画背景用
g.fillrectangle(blackbrush, rectx, recty, rectwidth, rectheight);
g.drawstring(text, font, whitebrush, textarea);
memorystream ms = new memorystream(); //保存为jpg类型
bitmap.save(ms, imageformat.jpeg); //输出处理后的图像,这里为了演示方便,我将图片显示在页面中了
bitmap.save(system.web.httpcontext.current.server.mappath("/" + "aa.jpg"), imageformat.jpeg); //保存到磁盘上
system.web.httpcontext.current.response.clear();
system.web.httpcontext.current.response.contenttype = "image/jpeg";
system.web.httpcontext.current.response.binarywrite(ms.toarray());
g.dispose();
bitmap.dispose();
image.dispose();
}
}
}