下面是一个将文本文件或者字符串转成图片的例子,调用方法:
实现的源代码
using System.IO;
using System.Drawing;
string textFile=Server.MapPath("~/Data.txt");
string imageFile = Server.MapPath("~/Data.png");
//记录记事本
using (StreamWriter sw = File.CreateText(textFile))
{
sw.WriteLine(TextBox1.Text);
sw.Flush();
sw.Close();
}
//生成图片
const int FixedWidth = 600;//期望的显示宽度
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("UTF-8"));
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, new System.Drawing.RectangleF(new System.Drawing.PointF(0, 0), sf));
image.Save(imageFile, System.Drawing.Imaging.ImageFormat.Png);
g.Dispose();
image.Dispose();
前台:
<asp:TextBox ID="TextBox1" runat="server" Width="600px" Height="100px"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="提交" onclick="Button1_Click" />
- 本文标题: 动态将文字生成图片,防止复制查看源码
- 文章分类:【.NET/Web】
- 非特殊说明,本文版权归【胡同里的砖头】个人博客 所有,转载请注明出处.
- 上一篇:js判断内容是否包含中文
- 下一篇: 错误:Base-64 字符数组的无效长度 错误原因