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

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

调用时很简单,
AddTextToImg("me.jpg","http://www.113317.com");



浙公网安备 33010602011771号