Creating Graphics On-The-Fly with ASP.NET

By Matt Duckhouse

This article describes how to use ASP.NET to create images on-the-fly for display within a Web page.

You are going to need IIS and the .NET framework installed on your machine in order to try the code out. I used Visual Studio.NET to create the code, but you can use Notepad just as easily. You just won't have your code coloured for you!

To demonstrate the technique, we are going to build an ASP.NET page to create a simple bar chart with three different bars, the height of each bar being selected by the user. The ASP.NET page creates a GIF image that is displayed on a Web page.


Screenshot of the bar chart drawer


The Basics

To insert an image into an HTML page you can simply use the <img src="image.gif"> notation. The image specified is then picked up from the Web server and displayed within the Web page. However, it is sometimes useful to be able to create an image on-the-fly based on some parameters received from a user rather than simply picking up a static image from the Web server. The information used to create the image could be from a form on a Web page or might be data which is collected from a database.

By specifying an ASP.NET page, rather than an image file within your IMG tag (<img src="imagecreator.aspx">), and coding the page to generate an image and then return it back to the browser, it is possible to create dynamic images on the fly. The .NET framework provides a Graphics class with all the functions you need to create an image from scratch. First, we are going to create the ASP.NET page, and then we will build a test harness to demonstrate the functionality.

Here is an overview of the process our ASP.NET page is going to run:

  1. Generate a blank 'Bitmap' object of the correct dimensions
  2. Draw our image (in this case a bar chart) on the Bitmap using the 'Graphics' object and the information received from the user
  3. Convert our completed image to GIF format
  4. Send the GIF to the output stream and back to the browser

The Code

We start off our ASP.NET page by defining the language that we are going to use, Visual Basic.NET in this instance, and then importing namespaces we are going to need later in the program. If you prefer C# then there is a C# version of this code included in the accompanying ZIP file.


<%@ Page Language="VB" %>
<%@ Import Namespace="System.Drawing" %>
<%@ Import Namespace="System.Drawing.Imaging" %>

Next, we create a subroutine which will be called as soon as the page is loaded.


<script language="VB" runat="server">

Sub Page_Load(sender As Object, e As EventArgs)

OK. The housekeeping functions are done; now we are into the real code. First, we create a new Bitmap object, passing the width and height of the graphic we wish to create, 200x200 pixels in this case.

	Dim objBitmap As New Bitmap(200,200)

Now we need to create a Graphics object in order to be able to draw on our newly created bitmap. We use the FromImage call of the Graphics object for this purpose.

	Dim objGraphic as Graphics = Graphics.FromImage(objBitmap)


Next, we need to create some brushes so we can paint on our canvas. We create 4 brushes one for each bar on our bar chart (red, blue and green) and white for the background colour. We also create a black pen to draw the horizontal and vertical axis on the chart.

	Dim redBrush    As New SolidBrush(Color.Red)
	Dim blueBrush   As New SolidBrush(Color.Blue)
	Dim greenBrush  As New SolidBrush(Color.Green)
	Dim whiteBrush  As New SolidBrush(Color.White)
	Dim blackPen    As New Pen(Color.Black, 2)

When you create a new bitmap, the background colour is set to black so we call FillRectangle to paint the whole of the background white.

	objGraphic.FillRectangle(whiteBrush, 0, 0, 200, 200)

Now that we have a white bitmap and some brushes, we can get painting. We use the DrawLine method to draw the horizontal and vertical axis.

	objGraphic.DrawLine(blackPen, New Point(0,195), New Point(195,195))
	objGraphic.DrawLine(blackPen, New Point(5,5),   New Point(5,200))

The next section of code calculates the height of each of the bars on the bar chart based on the parameters that the user has specified and uses FillRectangle() to draw the bars. We work out the highest value that the user has specified and then scale the other bars to fit on the graph.

	Dim sngHighestValue As Single
Dim sngHeight1 As Single, sngHeight2 As Single, sngHeight3 As Single
	Dim sngValue1 As Single, sngValue2 As Single, sngValue3 As Single

	sngValue1 = Convert.ToSingle(Request("v1"))
	sngValue2 = Convert.ToSingle(Request("v2"))
	sngValue3 = Convert.ToSingle(Request("v3"))

	If sngValue1 > sngValue2 Then
		sngHighestValue = sngValue1
	Else
		sngHighestValue = sngValue2
	End If
	If sngValue3 > sngHighestValue Then
		sngHighestValue = sngValue3
	End If
	If sngHighestValue = 0 Then sngHighestValue = 1

	sngHeight1 = (sngValue1 / sngHighestValue) * 190
	sngHeight2 = (sngValue2 / sngHighestValue) * 190
	sngHeight3 = (sngValue3 / sngHighestValue) * 190

	objGraphic.FillRectangle(redBrush,  10,194-sngHeight1,50,sngHeight1)
	objGraphic.FillRectangle(blueBrush, 70,194-sngHeight2,50,sngHeight2)
	objGraphic.FillRectangle(greenBrush,130,194-sngHeight3,50,sngHeight3)

Next, we need to change the page ContentType to let the browser know that we are sending back a GIF image.

       Response.ContentType = "image/gif"

And finally we save our bitmap in GIF format and send it back to the browser.

       objBitmap.Save (Response.OutputStream, ImageFormat.Gif)

End Sub

</script>

Now we save the whole file as 'BarChart.aspx' and put it into a directory on our Web server.

Testing the System

To test our new bar-chart-drawing ASP.NET page, we need to create a simple test harness. The test harness consists of an ASP.NET page with three text boxes into which the user can enter the heights of the bars on their chart and an IMG tag specifying the image source as BarChart.aspx and passing over the three parameters that the user specified. Here's the code:

Firstly, we need to output some text boxes for the user to enter values for his bar chart.


<%@ Page Language="VB" %>
<html>
<body>

<form action="ChartTest.aspx" action="POST">
Value 1: <input type="text" name="v1" value="<%= Request("v1") %>"><br>
Value 2: <input type="text" name="v2" value="<%= Request("v2") %>"><br>
Value 3: <input type="text" name="v3" value="<%= Request("v3") %>"><br><br>

<input type="submit" value="Redraw Bar Chart"><br><br>
</form>

Now we need to convert any values received from the user to numeric values so that we can pass them to our bar-chart-drawing ASP.NET page. If for some reason the conversion fails, for instance , if the user has entered nothing or an alphanumeric character, we will set the values to 0.

<script language="VB" runat="server">

	Dim sngValue1 As Single, sngValue2 As Single, sngValue3 As Single

Sub Page_Load()

	Try 
		sngValue1 = Convert.ToSingle(Request("v1")) 
	Catch
		sngValue1 = 0
	End Try

	Try 
		sngValue2 = Convert.ToSingle(Request("v2")) 
	Catch
		sngValue2 = 0
	End Try

	Try 
		sngValue3 = Convert.ToSingle(Request("v3")) 
	Catch
		sngValue3 = 0
	End Try

End Sub

</script>


Finally, we output the image using the IMG HTML tag with our ASP.NET page as the source.

<img src="BarChart.aspx?v1=<%= sngValue1 %>&v2=<%= sngValue2 %>&v3=<%= sngValue3 %>" width=200 height=200>

</body>
</html>


And that's it! We'll call the file 'ChartTest.aspx' and put it in the same directory as the 'BarChart.aspx' file on our Web server.

To test the system, simply enter the URL of the test harness page (for instance, http://localhost/ChartTest.aspx) into a browser. Remember, because ASP.NET pages are compiled the first time they are accessed it may take a few seconds to display the page the first time around. If you get a "Download this file" dialog box appear it probably means that you don't have the .NET framework installed on your machine. Take a look at Microsoft's developer site http://msdn.microsoft.com/ to download the framework.

You should see something similar to figure 1.


Figure 1 - Test Harness Screenshot

To test the graphic creator you simply need to enter different values into the boxes and hit the 'Redraw Bar Chart' button. When you have your ideal bar chart you can right click on the image and save it to your local hard drive as you would with any regular image.

What else can you do with this technique?

Once you have created your blank Bitmap and Graphics objects you can take advantage of the numerous methods provided by the Graphics class to draw anything you wish. For instance, the class has members relating to curves, polygons, ellipses and text rendering.

Most important, you can also take parameters passed to the ASP.NET page to modify what you draw on the canvas. You can find a complete list of Graphics class members in the MSDN library:

http://msdn.microsoft.com/library/en-us/cpref/html/frlrfSystemDrawingGraphicsMembersTopic.asp?frame=true

In the past I've used the technique described here to create line graphs, pie graphs and various other charts - in some cases pulling the data from a SQL Server database. By using the rotate and scale functions provided by the Graphics class, you can also manipulate existing images and present them to the Web user to download without having multiple copies of images stored on your Web server. For instance, you might have a master JPEG image stored on your Web server and allow the user to select the resolution they wish to download the image in. You can then use the scale functionality of the Graphic class to create the image in the appropriate size.

Also, by modifying the ContentType and specifying a different ImageFormat in your call to the Save method, you can create images in different formats, for instance, JPEGs or PNGs.

Within the source zip file I have included some examples of how the Graphics class can be used to produce different types of images. I have also included a C# version of the main demonstration.

Conclusion

The Graphic class of the .NET framework provides a rich collection of methods which allow an ASP.NET page to draw on a canvas and then output the resulting image to a browser in a number of different formats. The ASP.NET page can also accept parameters and use these to modify the image which is produced by the page.

About the Author

Matt Duckhouse lives and works in the United Kingdom. He develops Internet solutions for the automotive industry within the e-Business division of DCS Automotive. He can be reached at mattduckhouse@yahoo.co.uk.



Downloads

Comments

  • This is one of the best tutorials I have ever read!

    Posted by Esti on 12/02/2012 03:38am

    It explains every think so clearly and it is applicable! THANKS

    Reply
  • macrocas

    Posted by infenceHopWop on 10/24/2012 06:12pm

    A number of experts are surprised by the rise of internet sports betting and it displays no warning signs of decreasing. This type of betting related exercise probably won't be to the preference of some, but given that it is done properly, no bad thing happens. People enjoy the challenge, thrill and excitement of attempting to win money when they bet on sport and that will never change. [url=http://www.tellthemachine.com/content/popular-betting-techniques-used-internet-casinos]betting websites[/url] The variables are the payoffs for will to meet to times, and One of betting, obtaining who wins is $100.

    Reply
  • dot net nuke

    Posted by dot net nuke on 09/03/2012 01:36am

    I have read your blog and i got a very useful and knowledgeable information from your blog.its really a very nice article.You have done a great job . Thank you so much for sharing. dot net nuke

    Reply
  • dot net nuke

    Posted by dot net nuke on 08/20/2012 04:27am

    I have read your blog and i got a very useful and knowledgeable information from your blog.its really a very nice article.You have done a great job . Thank you so much for sharing. dot net nuke

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Today's agile organizations pose operations teams with a tremendous challenge: to deploy new releases to production immediately after development and testing is completed. To ensure that applications are deployed successfully, an automatic and transparent process is required. We refer to this process as Zero Touch Deployment™. This white paper reviews two approaches to Zero Touch Deployment--a script-based solution and a release automation platform. The article discusses how each can solve the key …

  • Learn How A Global Entertainment Company Saw a 448% ROI Every business today uses software to manage systems, deliver products, and empower employees to do their jobs. But software inevitably breaks, and when it does, businesses lose money -- in the form of dissatisfied customers, missed SLAs or lost productivity. PagerDuty, an operations performance platform, solves this problem by helping operations engineers and developers more effectively manage and resolve incidents across a company's global operations. …

Most Popular Programming Stories

More for Developers

RSS Feeds