首页 .NET/Web 动态将文字生成图片,防止复制查看源码

动态将文字生成图片,防止复制查看源码

作者:胡同里的砖头 围观群众:783 更新于:2013-12-19

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

实现的源代码

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】
  • 非特殊说明,本文版权归【胡同里的砖头】个人博客 所有,转载请注明出处.
留言评论
站点声明:
1、本站【胡同里的砖头】个人博客,借鉴网上一些博客模板,取其各优点模块自行拼装开发,本博客开发纯属个人爱好。
2、所有笔记提供给广大用户交流使用,可转载,可复制,纯个人开发所遇问题锦集记录使用
Copyright © huzlblog.com All Rights Reserved. 备案号:苏ICP备2021056683号-8