Thursday, January 15, 2009

Writing images directly into ASP.Net response stream

This is for all who wish to use as follows

<img src="image.aspx?text=yourtext"/>

in order to display your text beautifully as an image.

Implementation

This makes use of the concept of managed gdi drawing and direct stream handling.Here are the steps

  1. Create a new Page named Image.aspx.
  2. Remove its contens except the page directive.
    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Image.aspx.cs" Inherits="TextImageGenerator.Image" %>



  3. In the Page_Load handler do the following



    1. Create object of Bitmap


    2. Get Graphics object from the bitmap.


    3. Draw strings into the graphics object


    4. Save the bitmap into the output stream




Code



protected void Page_Load(object sender, EventArgs e)
{
Bitmap bitmap = new Bitmap(100, 100);
Graphics g = Graphics.FromImage(bitmap);
g.DrawString(Request.QueryString["text"] == null ? "joymon@gmail.com" : Request.QueryString["text"], SystemFonts.DefaultFont, Brushes.Red, new PointF(0, 0));
bitmap.Save(Response.OutputStream, ImageFormat.Jpeg);
}


Future enhancements




  • Changing size of the bitmap according to the length of the text and font styles using MeasureString.


  • Adding support for font styles and other parameters.



Sample can be downloaded here.

No comments: