DotNet2.0专题
关注DotNet,传播DotNet。
 1using System.Drawing;
 2using System.IO;
 3using System.Drawing.Imaging;
 4private void AddTextToImg(string fileName,string text)
 5{
 6if(!File.Exists(MapPath(fileName)))
 7{
 8throw new FileNotFoundException("The file don't exist!");
 9}

10
11if( text == string.Empty )
12{
13return;
14}

15//还需要判断文件类型是否为图像类型,这里就不赘述了
16System.Drawing.Image image = System.Drawing.Image.FromFile(MapPath(fileName));
17Bitmap bitmap = new Bitmap(image,image.Width,image.Height);
18Graphics g = Graphics.FromImage(bitmap);
19float fontSize = 12.0f//字体大小
20float textWidth = text.Length*fontSize; //文本的长度
21//下面定义一个矩形区域,以后在这个矩形里画上白底黑字
22float rectX = 0
23float rectY = 0;
24float rectWidth = text.Length*(fontSize+8);
25float rectHeight = fontSize+8;
26//声明矩形域
27RectangleF textArea = new RectangleF(rectX,rectY,rectWidth,rectHeight);
28Font font = new Font("宋体",fontSize); //定义字体
29Brush whiteBrush = new SolidBrush(Color.White); //白笔刷,画文字用
30Brush blackBrush = new SolidBrush(Color.Black); //黑笔刷,画背景用
31g.FillRectangle(blackBrush,rectX,rectY,rectWidth,rectHeight); 
32g.DrawString(text,font,whiteBrush,textArea);
33MemoryStream ms = new MemoryStream( );
34//保存为Jpg类型
35bitmap.Save(ms,ImageFormat.Jpeg);
36//输出处理后的图像,这里为了演示方便,我将图片显示在页面中了
37Response.Clear();
38Response.ContentType = "image/jpeg";
39Response.BinaryWrite( ms.ToArray() );
40g.Dispose();
41bitmap.Dispose();
42image.Dispose();
43}

44

调用时很简单,
AddTextToImg("me.jpg","http://www.113317.com");
posted on 2006-07-09 22:14  InitialC  阅读(230)  评论(0)    收藏  举报