萬盛學電腦網

 萬盛學電腦網 >> 網絡編程 >> asp編程 >> 將文本文件或者字符串轉成圖片

將文本文件或者字符串轉成圖片

   下面是一個將文本文件或者字符串轉成圖片的例子,調用方法:

  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();

  }

copyright © 萬盛學電腦網 all rights reserved