blfoley.com - all things development

Generate Text Images From ASP.net

3/10/2009

Here is a basic code sample for generating images based on text. Simply wrap this code in a http handler, add the query parameters and you'll be good to go. I have a complete solution with this code on codeplex. http://imagetext.codeplex.com/

Bitmap Bitmap = new Bitmap(Convert.ToInt16(context.Request.QueryString["w"]), Convert.ToInt16(context.Request.QueryString["h"]));
Graphics Graphic = Graphics.FromImage(Bitmap);

System.Drawing.Color Color;

string Font = "Rage Italic";
string Text = context.Request.QueryString["text"];

SolidBrush Brush = new SolidBrush(Color.White);
SolidBrush BrushBlack = new SolidBrush(Color.Black);

Graphic.FillRectangle(BrushBlack, 0, 0, Convert.ToInt16(context.Request.QueryString["w"]), Convert.ToInt16(context.Request.QueryString["h"]));
Graphic.TextRenderingHint =
TextRenderingHint.AntiAlias;

PointF Point = new PointF(5.0F, 5.0F);

Font font = new Font(Font, Convert.ToInt16(Convert.ToInt16(context.Request.QueryString["h"]) * .75), FontStyle.Italic, GraphicsUnit.Pixel);

Graphic.DrawString(Text, font, Brush, Point);

context.Response.ContentType = "image/jpeg";
Bitmap.Save(context.Response.OutputStream,
ImageFormat.Jpeg);

Related Postings