Download and view my resume (PDF)

Thursday, April 22, 2010

Generate a Bitmap/PNG With A Text Message

Some applications need to generate images with bits of text on them. In C#, this is very easy. Here is a method which generates a rectangular (256x256) bitmap image with some text written on it.
static public Bitmap GetMessageBitmap(string message)
{
Bitmap bitmap = new Bitmap(256, 256);
Graphics graphics = Graphics.FromImage(bitmap);
graphics.DrawString(message, new Font("Tahoma", 12), Brushes.Black, new RectangleF(0,0,256,256));
return bitmap;
}
Here is a method which turns the bitmap into a PNG image and writes it out to an HTTPListenerResponse.
static public WriteToResponse(HttpListenerContext context)
{
context.Response.ContentType = "image/png";

byte[] imgArray = Utility.Bitmap2Bytes(GetMessageBitmap(request), ImageFormat.Png);
context.Response.ContentLength64 = imgArray.Length;
context.Response.OutputStream.Write(imgArray, 0, imgArray.Length);
context.Response.OutputStream.Close();
}
I am not a fan of Microsoft either from the technology perspective or from the business perspective, but I have to say I think they did a pretty good job with C#. The API is complete and robust; the runtime is very fast; the features of the language are a big step forward from, say, Java. At the end of the day, a computer language is a tool, and tools are supposed to help workers get jobs done, and I was able to make images with text on them easily using C#; thus, I consider C# to be a good tool.

My only complaint is that to use C# I have to use Windows and Visual Studio -- two tools of which I am much less fond. (What? Mono? Huh?)

No comments:

Post a Comment