Sunday, February 22, 2009

How-To Create Dynamic Image From Text

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
}

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

Source : http://blog.sb2.fr/post/2008/12/23/How-To-Create-Dynamic-Image-From-Text.aspx

No comments:

Post a Comment