Monday, October 27, 2008

Basic of GDI+ and Graphics in ASP.NET

Introduction

In this article, I will explain about GDI+ in .NET Framework. If you haven't heard about GDI+, then GDI+ is a set of classes in .NET framework that deal with graphics. You can use GDI+ to draw custom drawing on the screen. GDI provides a layer of abstraction, hiding the differences between different video cards.

You simply need to call the Windows API function to do the specific task, and internally the GDI figures out how to get to the client's particular video card to do whatever that you want.

Although GDI exposes a relatively high level API to developers, it is still an API that based on the old Windows API with C style functions. GDI+ sits as a layer between GDI and your application providing more intuitive and inheritance based object model.

GDI+ is generally considered a Windows technology. However, some of the new GDI+ features make this technology an excellent choice for Web applications, enabling developers to generate images, graphs, diagrams, and much more.

Drawing Shapes with GDI+ in ASP.NET

In this example below, we will try to draw some simple rectangle and ellipse using GDI+ in ASP.NET
Start by Adding new ASPX page and named it Image.aspx. Add reference to System.Drawing and System.Drawing.Imaging. Paste the code below to your Page_Load Event.

Bitmap bmp = new Bitmap(100, 300);

Graphics dc = Graphics.FromImage(bmp);
Pen bluePen = new Pen(Color.Blue, 3);
dc.DrawRectangle(bluePen, 0, 0, 50, 50);

Pen redPen = new Pen(Color.Red, 2);
dc.DrawEllipse(redPen, 0, 50, 80, 60);
Response.ContentType = "image/gif";
bmp.Save(Response.OutputStream, ImageFormat.Gif);

In the code above, you can see that you draw a rectangle at cordinates(0,0) and with the width and height of 50.
For the Ellipse, we draw it at cordinates(0,50) and the width 80 and height 50. Note that coordinates(x,y) translates to x pixels to the right and y pixels down from the top-left corner of the images

When you try to view the page, you can see that the output of the page is an image. And if you try to add some code in the Aspx page such as Header "This is my image". You won't be able to see that in the browser. The reason is because we set the Response.OutputStream to ImageFormat.Gif.

To fix this, just create new aspx page and named it Test.aspx
After that add the following code
This is my image

<BR>
<img src="Image.aspx" />

Drawing String with GDI+ and ASP.NET

Have you ever wondered when you try to view someone else page, they actually write down the emailaddress in image format to prevent spam from robots.
Nah, in the example below, I will show you how to do that


Image.aspx

Bitmap bmp = new Bitmap(300, 30);

Graphics dc = Graphics.FromImage(bmp);
Font f = new Font("Verdana", 11);
dc.DrawString("myemail@mydomainname.com", f, Brushes.Yellow, 0, 0);
bmp.Save(Response.OutputStream, ImageFormat.Gif);

Test.aspx
 Please email me at

<BR />
<IMG src="Image.aspx" />

Output

Pretty Easy right. Now you can start doing this for your website. So rather than showing your email addresses as text, you can change it to image. This will prevent your email address being spam by web robot.

Creating Captcha using GDI+ and ASP.NET

If you haven't heard about Captcha, then probably I can explain a bit about that. Have you seen in most of the websites especially forums or Registration form, there is a small images showing some text and you need to verify the text before you can actually register. Nah, that is called as Captcha image.

The purpose of the Captcha is to defeat the robots from submitting to the form automatically.

In the code below, I will show you how

 Random Rand = new Random();

// Create a new random number between the specified range
int iNum= Rand.Next(10000, 99999);
Bitmap Bmp = new Bitmap(90, 50);
Graphics gfx = Graphics.FromImage(Bmp);
Font fnt = new Font("Verdana", 12);

// Draw the random number
gfx.DrawString(RandNum.ToString(), fnt, Brushes.Yellow, 15, 15);
Bmp.Save(Response.OutputStream, ImageFormat.Gif);


This is all the code we need. A random number between 10000 and 99999 is generated and displayed as a graphic so robots can't pass it.

Now you would only need a text box where the visitor should type the number and a few lines of code to compare it with the random value inside iNum.

Technology is getting more advanced from days to days and so are the spammer. Now, there are smart robots actually can read the text from the images by using character recognition. We can actually try to make things harder for them to break. We can add few lines into the images to fool the robot.

 Random Rand = new Random();

int iNum = Rand.Next(10000, 99999);
Bitmap Bmp = new Bitmap(90, 50);
Graphics Gfx = Graphics.FromImage(Bmp);
Font Fnt = new Font("Verdana", 12, FontStyle.Bold);
Gfx.DrawString(iNum.ToString(), Fnt, Brushes.Yellow, 15, 15);
// Create random numbers for the first line
int RandY1 = Rand.Next(0, 50);
int RandY2 = Rand.Next(0, 50);

// Draw the first line
Gfx.DrawLine(Pens.Yellow, 0, RandY1, 90, RandY2);
// Create random numbers for the second line
RandY1 = Rand.Next(0, 50);
RandY2 = Rand.Next(0, 50);
// Draw the second line
Gfx.DrawLine(Pens.Yellow, 0, RandY1, 90, RandY2);
Bmp.Save(Response.OutputStream, ImageFormat.Gif);
Session["Number"] = iNum;


From the image above, you can see that we as human can still read the image. However robot might have some difficulties on reading it. It is up to your imagination really, how you can fool the robots. You can draw some dots, rectangle and etc.

Now, for the aspx part.
<SCRIPT RUNAT=server>

protected void Button1_Click(object sender, EventArgs e)
{
if (txtNumber.Text.Trim() == Session["Number"].ToString().Trim())
{
Response.Write("Match");
}
else
{
Response.Write("Not Match");
}
}
SCRIPT>
<BODY>
<FORM ID="form1" RUNAT="server">
<DIV>
<BR />
<IMG src="Default.aspx" />
<BR />
Please Enter the Image number
<ASP:TEXTBOX ID="txtNumber" RUNAT="server">ASP:TEXTBOX>DIV>
<ASP:BUTTON ID="Button1" RUNAT="server" TEXT="Button" ONCLICK="Button1_Click" />
FORM>
BODY>

As you can see we store the random numbers in Session variables. Then on your page, we just compare the Session variables with the input that the users provide, If it match then we can make sure that the form is not filled by the robots, and you can proceed to the next step.

Conclusion

GDI+ is a powerful set of classes that dealing with graphics and it is impossible to discuss all the powerful features here. Microsoft has provides lots of methods and properties in GDI+ that you can use and actually the only limit is your imagination. Happy GDI ing

Download Source Code

No comments: