将文本文件或者字符串转成图片

2015-08-12 16:01:26来源:作者:人点击

   下面是一个将文本文件或者字符串转成图片的例子,调用方法:

  C# 代码

  ConvertTextFileToImage(Server.MapPath("~/Data.txt"), Server.MapPath("~/Data.png"));

  实现的源代码:

  C# 代码

  protected void ConvertTextFileToImage(String textFile, String imageFile)

  {

  const int FixedWidth = 1024;//期望的显示宽度

  System.Drawing.Font drawFont = new System.Drawing.Font("宋体", 12);

  System.Drawing.Bitmap image = new System.Drawing.Bitmap(1, 1);

  System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(image);

  String text = System.IO.File.ReadAllText(textFile, System.Text.Encoding.GetEncoding("GB2312"));

  System.Drawing.SizeF sf = g.MeasureString(text, drawFont, FixedWidth);

  System.Drawing.Size showSize = new System.Drawing.Size(Convert.ToInt32(sf.Width), Convert.ToInt32(sf.Height));

  image = new System.Drawing.Bitmap(image, showSize);

  g = System.Drawing.Graphics.FromImage(image);

  g.Clear(System.Drawing.Color.White);

  g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;

  g.DrawString(text, drawFont, System.Drawing.Brushes.Black, newSystem.Drawing.RectangleF(new System.Drawing.PointF(0, 0), sf));

  image.Save(imageFile, System.Drawing.Imaging.ImageFormat.Png);

  g.Dispose();

  image.Dispose();

  }

最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台