1 /// <summary>
2 /// 给图片添加文字水印
3 /// </summary>
4 /// <param name="stream">图片流</param>
5 /// <param name="text">文字水印</param>
6 /// <param name="watermarkStatus">图片水印位置 0=不使用 1=左上 2=中上 3=右上 4=左中 9=右下</param>
7 /// <param name="fontsize">字体大小</param>
8 /// <param name="angle">旋转角度(顺时针)</param>
9 /// <returns></returns>
10 public static Image AddText2Image(Stream stream, string text, int watermarkStatus, int fontsize, int angle)
11 {
12 Image img = Image.FromStream(stream);
13 using (var g = Graphics.FromImage(img))
14 using (var brush = new SolidBrush(Color.Red))
15 {
16 Font font = new Font("宋体", fontsize, FontStyle.Regular, GraphicsUnit.Pixel);
17 g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
18 g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
19 var sizeF = g.MeasureString(text, font);
20
21 float xpos = 0;
22 float ypos = 0;
23 switch (watermarkStatus)
24 {
25 case 1:
26 xpos = (float)img.Width * (float).01;
27 ypos = (float)img.Height * (float).01;
28 break;
29 case 2:
30 xpos = ((float)img.Width * (float).50) - (sizeF.Width / 2);
31 ypos = (float)img.Height * (float).01;
32 break;
33 case 3:
34 xpos = ((float)img.Width * (float).99) - sizeF.Width;
35 ypos = (float)img.Height * (float).01;
36 break;
37 case 4:
38 xpos = (float)img.Width * (float).01;
39 ypos = ((float)img.Height * (float).50) - (sizeF.Height / 2);
40 break;
41 case 5:
42 xpos = ((float)img.Width * (float).50) - (sizeF.Width / 2);
43 ypos = ((float)img.Height * (float).50) - (sizeF.Height / 2);
44 break;
45 case 6:
46 xpos = ((float)img.Width * (float).99) - sizeF.Width;
47 ypos = ((float)img.Height * (float).50) - (sizeF.Height / 2);
48 break;
49 case 7:
50 xpos = (float)img.Width * (float).01;
51 ypos = ((float)img.Height * (float).99) - sizeF.Height;
52 break;
53 case 8:
54 xpos = ((float)img.Width * (float).50) - (sizeF.Width / 2);
55 ypos = ((float)img.Height * (float).99) - sizeF.Height;
56 break;
57 case 9:
58 xpos = ((float)img.Width * (float).99) - sizeF.Width;
59 ypos = ((float)img.Height * (float).99) - sizeF.Height;
60 break;
61 }
62 g.ResetTransform();
63 g.TranslateTransform(xpos, ypos);
64 g.RotateTransform(angle);
65 g.DrawString(text, font, brush, new PointF(-sizeF.Width / 2, -sizeF.Height / 2));
66 }
67 return img;
68 }