C#图像处理(1):在图片上加文字和改变文字的方向

C#在图片上加文字,代码如下:

 1         /// <summary>
 2         /// 图片上方加文字,文字将会被180度反转
 3         /// </summary>
 4         /// <param name="Img">待处理图片</param>
 5         /// <param name="WriteString">写入的字符串</param>
 6         /// <param name="UpMargin">180度反转后文字顶部距离上边缘距离</param>
 7         /// <param name="RightMargin">文字最左边距离右边缘距离</param>
 8         /// <returns>Bitmap</returns>
 9         public Bitmap WriteUp(Image Img, string WriteString, int UpMargin, int RightMargin)
10         {
11             return WriteUp(Img, WriteString, UpMargin, RightMargin, "宋体", 20);
12         }
13 
14         /// <summary>
15         /// 图片上方加文字,文字将会被180度反转
16         /// </summary>
17         /// <param name="Img">待处理图片</param>
18         /// <param name="WriteString">写入的字符串</param>
19         /// <param name="UpMargin">180度反转后文字顶部距离上边缘距离</param>
20         /// <param name="RightMargin">文字最左边距离右边缘距离</param>
21         /// <param name="FontType">字体类型</param>
22         /// <param name="FontSize">字体大小</param>
23         /// <returns></returns>
24         public Bitmap WriteUp(Image Img, string WriteString, int UpMargin, int RightMargin, string FontType, int FontSize)
25         {
26             //获取图片宽高
27             int Width = Img.Width;
28             int Height = Img.Height;
29             //获取图片水平和垂直的分辨率
30             float dpiX = Img.HorizontalResolution;
31             float dpiY = Img.VerticalResolution;
32             //创建一个位图文件
33             Bitmap BitmapResult = new Bitmap(Width, Height, PixelFormat.Format24bppRgb);
34             //设置位图文件的水平和垂直分辨率  与Img一致
35             BitmapResult.SetResolution(dpiX, dpiY);
36             //在位图文件上填充一个矩形框
37             Graphics Grp = Graphics.FromImage(BitmapResult);
38             System.Drawing.Rectangle Rec = new System.Drawing.Rectangle(0, 0, Width, Height);
39             //向矩形框内填充Img
40             Grp.DrawImage(Img, 0, 0, Rec, GraphicsUnit.Pixel);
41 
42 
43             //平移Graphics对象
44             Grp.TranslateTransform(Width - RightMargin, UpMargin);
45             //设置Graphics对象的输出角度以改变文字方向
46             Grp.RotateTransform(180);
47             //设置文字填充颜色
48             Brush brush = Brushes.Black;
49             //旋转显示文字
50             Grp.DrawString(WriteString, new Font(FontType, FontSize, GraphicsUnit.Pixel), brush, 0, 0);
51             //恢复全局变换矩阵
52             Grp.ResetTransform();
53             Grp.Dispose();
54             GC.Collect();
55             return BitmapResult;
56         }

 

posted on 2014-08-18 15:04  吴培洪  阅读(2173)  评论(0编辑  收藏  举报

导航