Go to DotNetFunda.com
 Welcome, Guest!  
LoginLogin  
Take a break and be productive! read technical jokes.
 Skip Navigation Links Home > Articles > ASP.NET > Creating dynamic image from text

All Articles | Submit Article |

Creating dynamic image from text

 Posted on: 12/21/2008 6:12:05 AM by SheoNarayan | Views: 7527 | Category: ASP.NET | Level: Intermediate | Print Article
This article describe how to create an image from text in asp.net with C#.

 Get Career Counseling  
DotNetFunda.Com brings you a FREE Career Counseling section where you can ask any type of career related question. Ask now!

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.


Interesting?   Bookmark and Share


About Sheo Narayan

Experience:6 year(s)
Home page:http://sheonarayan.myfunda.net/
Member since:Tuesday, July 08, 2008
Biography:Throughout 1st in all educational exams.
Major qualifications: HDCS, ADCA, MCA, MCTS
Location: Hyderabad, India
 Latest post(s) from SheoNarayan

   ◘ Using PageMethods and JSON in ASP.NET AJAX to work with data posted on 7/3/2009 6:38:08 PM
   ◘ Ensuring button is clicked only once, Confirmation and Please wait message for ASP.NET Form posted on 7/3/2009 3:34:15 PM
   ◘ Setting up Start Options in Visual Studio and Visual Web Developer posted on 6/28/2009 7:53:02 AM
   ◘ Website vs Web Application - Embedded resources posted on 6/23/2009 10:10:20 PM
   ◘ Adding removing xml attribute from XML File in .NET posted on 6/21/2009 12:55:43 AM


Response(s) to this Article
Posted by: Raja | Posted on: 03 Jan 2009 06:25:53 PM
Cool Idea and very useful. I think we can encrypt the email with some other encryption mechanism to make it more secure.

Thanks

 Submit Article

About Us | Contact Us | Privacy Policy | Terms of Use | Link Exchange | Members | Go Top
All rights reserved to DotNetFunda.Com. Logos, company names used here if any are only for reference purposes and they may be respective owner's right or trademarks.
(Best viewed in IE 6.0+ or Firefox 2.0+ at 1024 * 768 or higher)