在Asp.net中为图像加入水印信息
程序员文章站
2022-07-01 15:51:47
using system.drawing;
using system.io;
using system.drawing.imaging;
private void...
using system.drawing; using system.io; using system.drawing.imaging; private void addtexttoimg(string filename,string text) { if(!file.exists(mappath(filename))) { throw new filenotfoundexception("the file don't exist!"); } if( text == string.empty ) { return; } //还需要判断文件类型是否为图像类型,这里就不赘述了,前端框架分享 system.drawing.image image = system.drawing.image.fromfile(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); //输出处理后的图像,这里为了演示方便,我将图片显示在页面中了 response.clear(); response.contenttype = "image/jpeg"; response.binarywrite( ms.toarray() ); g.dispose(); bitmap.dispose(); image.dispose(); }
调用时很简单,前端ui分享
addtexttoimg("me.jpg","程序人生https://www.iteye.com/topic/1132907/");
一切ok了,感觉.net确实好强大,这些功能在asp中可是奢侈品了,而在.net环境中却能轻而易举的完成!