CODEDIGEST
Home » CodeDigest
Search
 

Technologies
 

Generate image from a string in C#. ASP.Net
Submitted By Satheesh Babu B
On 11/4/2008 8:23:02 AM
Tags: asp.net,C#,CodeDigest,httphandler  

The below code snippet will help us to display a string as an image in ASP.Net page. In the below code snippet, we first create Bitmap object with dimension of the image and use Graphics class in System.Drawing namespace to write the string in the created bitmap object. The created bitmap object is then converted to byte array and displayed in the page.

Refer the below code for complete understanding.

 

<%@ WebHandler Language="C#" Class="GenerateImage" %>

 

using System;

using System.Web;

using System.Drawing;

using System.IO;

 

public class GenerateImage : IHttpHandler {

   

    public void ProcessRequest (HttpContext context) {

        string strDisplay = "CodDigest.Com";

        Bitmap bmpOut = new Bitmap(200, 50);

        Graphics g = Graphics.FromImage(bmpOut);

        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

        g.FillRectangle(Brushes.Black,0,0,200,50);

        g.DrawString(strDisplay, new Font("Verdana", 18), new SolidBrush(Color.White), 0, 0);      

 

        MemoryStream ms = new MemoryStream();       

        bmpOut.Save(ms, System.Drawing.Imaging.ImageFormat.Png);

        byte[] bmpBytes = ms.GetBuffer();

        bmpOut.Dispose();

        ms.Close();

        context.Response.BinaryWrite(bmpBytes);

        context.Response.End();

 

    }

 

    public bool IsReusable {

        get {

            return false;

        }

    }

 

}

 

Do you have a working code that can be used by anyone? Submit it here. It may help someone in the community!!

Recent Codes
  • View All Codes..