web 2.0

How-To Create Dynamic Image From Text

Hi,

In this article I’ll provide a simple class in order to Create Dynamic Image From Text, which should be pretty useful for email obfuscation for example.

Default.aspx (2)

The TextImage Class

public class TextImage
{
    #region Public Properties

    public Color TextColor { get; set; }
    public Color BackColor { get; set; }
    public Font TextFont { get; set; }
    public String Text { get; set; }

    #endregion

    #region Private Properties

    private Brush TextBrushStyle { get; set; }
    private Brush BackBrushStyle { get; set; }

    #endregion

    #region Constructors

    public TextImage(String text)
    {
        Text = text;
        TextColor = Color.Black;
        BackColor = Color.White;
        TextFont = new Font("Arial", 18, FontStyle.Bold);
    }
    public TextImage(String text, Color textColor, Color backColor, Font textFont)
    {
        Text = text;
        TextColor = textColor;
        TextFont = textFont;
        BackColor = backColor;
    }

    #endregion


    #region Public Methods

    public Bitmap Process()
    {
        TextBrushStyle = new SolidBrush(TextColor);
        BackBrushStyle = new SolidBrush(BackColor);

        float f = TextFont.Size * 72 / 96;
        Bitmap tmp = new Bitmap(Text.Length * (int)f, TextFont.Height);
        using (Graphics graphic = Graphics.FromImage(tmp))
        {
            graphic.FillRectangle(BackBrushStyle, 0, 0, tmp.Width, tmp.Height);
            graphic.DrawString(Text, TextFont, TextBrushStyle, new PointF(0, 0));
        }
        return tmp;
    }
    public void WriteTo(Stream stream)
    {
        Bitmap bmp = Process();
        if (bmp == null) return;
        bmp.Save(stream, ImageFormat.Jpeg);
    }
    public void WriteTo(String filename)
    {
        Bitmap bmp = Process();
        if (bmp == null) return;
        bmp.Save(filename, ImageFormat.Jpeg);
    }

    #endregion
}

Sample Usage

protected void Page_Load(object sender, EventArgs e)
{
    Response.ContentType = "image/jpeg";
    TextImage img = new TextImage("Hello How Are You ??");
    img.BackColor = Color.White;
    img.TextColor = Color.Red;
    img.WriteTo(Response.OutputStream);
}

 

Hope this help’s!



Views(1413)

kick it on DotNetKicks.com

Share/Save/Bookmark Subscribe

Currently rated 4.0 by 1 people

  • Currently 4/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

C#

Comments

Technorati Profile