Creating dynamic image from text

SheoNarayan
Posted by in ASP.NET category on for Intermediate level | Views : 21118 red flag

This article describe how to create an image from text in asp.net with C#.
Introduction

These days we all get spam emails in our inbox. There are several ways from where automated robots gather these email ids. One of them is from the web page. These automated robots are programmed to filter the content from web page and store the email ids or phone numbers into their database. Later on these email ids are used to send automated spam emails.


To avoid robots from gathering email ids from the webpage, we can write them as image by dynamically generating it on the fly with the help of ASP.NET with C#. To dynamically generate the image on the fly, we shall use .ashx file. ASHX files are HTTP handlers written using .NET. The idea here is to pass the encrypted string to the .ashx file and after decrypting the string generate the image on the fly.

Create .ashx file

First we need to create .ashx file. The way we create .aspx file in the same way we can create .ashx file (create Generic Handler from the Templates dialog box). I have created a WriteTextAsImage.ashx file. As soon as you create this file, you will see two methods by default. These are ProcessRequest and IsReusable.


See following code snippet. 


using System;

using System.Web;

using System.Drawing;


public class WriteTextAsImage : IHttpHandler {


public void ProcessRequest(HttpContext context)

{

context.Response.ContentType = "image/jpeg";

string textToWrite = context.Request.QueryString["text"].ToString();

textToWrite = utilityFunctions.Decrypt(textToWrite); // decrypt the string

if (textToWrite.Trim().Length > 0)

{

Bitmap image = new Bitmap(400, 30);

Graphics g = null;

try

{

g = Graphics.FromImage(image);

Font f = new Font("Arial", 10, FontStyle.Regular);

SolidBrush b = new SolidBrush(Color.White);

g.FillRectangle(b, 0, 0, 400, 30);

g.DrawString(textToWrite, f, Brushes.Blue, 2, 5);


f.Dispose();

image.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);


}

catch (Exception ee)

{

context.Response.Write(ee.Message.ToString());

}

finally

{

image.Dispose();

g.Dispose();

}

}

}


public bool IsReusable {

get {

return true;

}

}


}

Let me explain the above code snippets in the in the simple steps.

  1. Use the System.Drawing namespace.

  2. In the ProcessRequest method, as we are going to create an image with the help of this handler file, set the ContextType as "image/jepg". Content type is nothing but the HTTP MIME type, for more details about several MIME types see this article http://msdn.microsoft.com/en-us/library/ms775147.aspx

  3. Get the text to write as as image from the querystring (text).

  4. Decrypt it (because we shall pass the encrypted string to this page so decrypt it to get the actual string)

  5. Create a new bitmap image using BitMap object.

  6. Create a graphic object from the bitmap.

  7. Create Font object with the desired style in which we want to write text.

  8. By default, the BitMap object is created as black backgroud, so lets make it white. To do that create SolidBrush object and fill the graphic object with the brush using FillRectangle method.

  9. Finally draw the text on the graphic by calling DrawString method and passing text to write, font, color and other padding parameters.

  10. Till now we have the graphic object, now save it as the OutputStream. To do that call the save method of the bitmap object and pass stream and image format as parameter. 

  11. We should never forget to dispose the object we have instantiated while creating the object, so dispose them using Dispose method of respective objects.

  12. IsReusable method indicates whether another request can use the IHttpHandler instance. I am returning true so that other requests can also use this instance of the IHttpHandler.


Function to encrypt and decrypt the string. Following functions to encrypt and decrypt string is simple, you can use more complex encryption and decryption mechanism in real application to get more security of the string you pass.


public class utilityFunctions { // simply encrypt the string

public static string Encrypt(string text)

{

byte[] bytes = Encoding.ASCII.GetBytes(text);

for (int i = 0; i < bytes.Length; i++)

{

bytes[i] = Convert.ToByte(Convert.ToInt64(bytes[i]) + 5);

}

return Encoding.ASCII.GetString(bytes);

}


// simple decrypt the string

public static string Decrypt(string text)

{

byte[] bytes = Encoding.ASCII.GetBytes(text);

for (int i = 0; i < bytes.Length; i++)

{

bytes[i] = Convert.ToByte(Convert.ToInt64(bytes[i]) - 5);

}

return Encoding.ASCII.GetString(bytes);

} }

Using .ashx file

So our .ashx file are ready to be used to create dynamic image provided it is passed a querystring name "text". Now, lets see how to use this file.

<img alt="Contact Details" title="Contact Details"

src="/WriteTextAsImage.ashx?text=<%= utilityFunctions.Encrypt("yourname@myfunda.net") %>" />

The actual img tag will appear like following in the page source.

<img alt="Conact Details" title="Conact Details"

src="/WriteTextAsImage.ashx?text=~tzwsfrjEr~kzsif3sjy" />

To use this file, we need to simply specify the src attribute of img element and pass the text(encrypted) to write as its querystring. If you followed the exact step and have implemented above code, your image should appear like below in the browser.


Hope this article will help you to avoid spam by creating email id and other information as image. Thank you for reading.

Page copy protected against web site content infringement by Copyscape

About the Author

SheoNarayan
Full Name: Sheo Narayan
Member Level: HonoraryPlatinum
Member Status: Administrator
Member Since: 7/8/2008 6:32:14 PM
Country: India
Regards, Sheo Narayan http://www.dotnetfunda.com
http://www.snarayan.com
Ex-Microsoft MVP, Author, Writer, Mentor & architecting applications since year 2001. Connect me on http://www.facebook.com/sheo.narayan | https://twitter.com/sheonarayan | http://www.linkedin.com/in/sheonarayan

Login to vote for this post.

Comments or Responses

Posted by: Raja on: 1/3/2009
Cool Idea and very useful. I think we can encrypt the email with some other encryption mechanism to make it more secure.

Thanks

Login to post response

Comment using Facebook(Author doesn't get notification)