Go to DotNetFunda.com
 Online : 1319 |  Welcome, Guest!   Login
 
Home > Articles > ASP.NET > Creating dynamic image from text

Submit Article | Articles Home | Search Articles |

Creating dynamic image from text

red flag  Posted on: 12/21/2008 6:12:05 AM by SheoNarayan | Views: 10592 | Category: ASP.NET | Level: Intermediate


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.


If you like this article, subscribe to our RSS Feed. You can also subscribe via email to our Interview Questions, Codes and Forums section.

Found interesting? Add this to:

| More



Please Sign In to vote for this post.

 
Latest post(s) from SheoNarayan

Latest Articles

About Sheo Narayan

Experience:8 year(s)
Home page:http://www.snarayan.com
Member since:Tuesday, July 08, 2008
Level:HonoraryPlatinum
Status: [Administrator]
Biography:Throughout 1st in all educational exams.
Major qualifications: HDCS, ADCA, MCA, MCTS
Developing and architecting applications in Microsoft technologies since year 2001.
Location: Hyderabad, India
 Response(s)
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 | The Team | Advertise | Contact Us | Testimonials | Privacy Policy | Terms of Use | Link Exchange | Members | Go Top
General Notice: If you found plagiarised (copied) contents on this page, please let us know the original source along with your correct email id (to communicate) for further action.
Copyright © DotNetFunda.Com. All Rights Reserved. Copying or mimicking the site design and layout is prohibited. Logos, company names used here if any are only for reference purposes and they may be respective owner's right or trademarks. | 9/3/2010 3:57:44 AM