有時(shí)候保存文本容易丟失,相對(duì)保存到圖片上,不容易被修改。今天在做xml導(dǎo)入txt,想到了把生成txt的內(nèi)容導(dǎo)成一張圖片,就說(shuō)一下導(dǎo)出圖片的方法:
1 void ConvertTextFileToImage(String textFile, String imageFile)
2 {
3 //設(shè)置畫(huà)布字體
4 System.Drawing.Font drawFont = new System.Drawing.Font("宋體", 12);
5 //實(shí)例一個(gè)畫(huà)布起始位置為1.1
6 System.Drawing.Bitmap image = new System.Drawing.Bitmap(1, 1);
7 System.Drawing.Graphics g = System.Drawing.Graphics.fromImage(image);
8 //讀取文本內(nèi)容 原理就跟水印字體一樣.o(∩_∩)o 哈哈....
9 String text = System.IO.File.ReadAllText(textFile, Encoding.GetEncoding("GB2312"));
10 System.Drawing.SizeF sf = g.MeasureString(text, drawFont, 1024); //設(shè)置一個(gè)顯示的寬度
11 image = new System.Drawing.Bitmap(image, new System.Drawing.Size(Convert.ToInt32(sf.Width), Convert.ToInt32(sf.Height)));
12 g = System.Drawing.Graphics.fromImage(image);
13 g.Clear(System.Drawing.Color.White);
14 g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;
15 g.DrawString(text, drawFont, System.Drawing.Brushes.Black, new System.Drawing.RectangleF(new System.Drawing.PointF(0, 0), sf));
16 image.Save(imageFile, System.Drawing.Imaging.ImageFormat.Png);
17 g.Dispose();
18 image.Dispose();
19 }