zoukankan      html  css  js  c++  java
  • c#中输入文本文字,将输入的文字生成图片

    private void button1_Click(object sender, EventArgs e)
    {
    //获取文本
    string text = this.txtName.Text;

    //得到Bitmap(传入Rectangle.Empty自动计算宽高)
    Bitmap bmp = TextToBitmap(text, this.txtName.Font, Rectangle.Empty, this.txtName.ForeColor, this.txtName.BackColor);

    //用PictureBox显示
    this.pictureBox1.Image = bmp;

    //保存到桌面save.jpg
    string directory = System.Environment.GetFolderPath(System.Environment.SpecialFolder.DesktopDirectory);
    bmp.Save(directory + "\save.jpg", ImageFormat.Jpeg);
    }
    //定义一个方法
    /// <summary>
    /// 把文字转换才Bitmap
    /// </summary>
    /// <param name="text"></param>
    /// <param name="font"></param>
    /// <param name="rect">用于输出的矩形,文字在这个矩形内显示,为空时自动计算</param>
    /// <param name="fontcolor">字体颜色</param>
    /// <param name="backColor">背景颜色</param>
    /// <returns></returns>
    private Bitmap TextToBitmap(string text, Font font, Rectangle rect, Color fontcolor, Color backColor)
    {
    Graphics g;
    Bitmap bmp;
    StringFormat format = new StringFormat(StringFormatFlags.NoClip);
    if (rect == Rectangle.Empty)
    {
    bmp = new Bitmap(1, 1);
    g = Graphics.FromImage(bmp);
    //计算绘制文字所需的区域大小(根据宽度计算长度),重新创建矩形区域绘图
    SizeF sizef = g.MeasureString(text, font, PointF.Empty, format);

    int width = (int)(sizef.Width + 1);
    int height = (int)(sizef.Height + 1);
    rect = new Rectangle(0, 0, width, height);
    bmp.Dispose();

    bmp = new Bitmap(width, height);
    }
    else
    {
    bmp = new Bitmap(rect.Width, rect.Height);
    }

    g = Graphics.FromImage(bmp);

    //使用ClearType字体功能
    g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
    g.FillRectangle(new SolidBrush(backColor), rect);
    g.DrawString(text, font, Brushes.Black, rect, format);
    return bmp;
    }

  • 相关阅读:
    java几种数据的默认扩容机制
    web.xml配置详解
    Bootstrap文件上传组件
    JAVA四则运算算法
    Oracle 和 mysql 的批量操作Sql语句 的区别
    JAVA使用ItextPDF
    c# 状态机实现
    c++11模拟boost元占位符placeholder
    vs2012 函数参数内存对齐引发编译错误
    windows下matplotlib编译安装备忘
  • 原文地址:https://www.cnblogs.com/hbh123/p/5236092.html
Copyright © 2011-2022 走看看