asp tutorials, asp.net tutorials, sample code, and Microsoft news from 15Seconds
Data Access  |   Troubleshooting  |   Security  |   Performance  |   ADSI  |   Upload  |   Email  |   Control Building  |   Component Building  |   Forms  |   XML  |   Web Services  |   ASP.NET  |   .NET Features  |   .NET 2.0  |   App Development  |   App Architecture  |   IIS  |   Wireless
 
Pioneering Active Server
 Power Search








Active News
15 Seconds Weekly Newsletter
• Complete Coverage
• Site Updates
• Upcoming Features

More Free Newsletters
Reference
News
Articles
Archive
Writers
Code Samples
Components
Tools
FAQ
Feedback
Books
Links
DL Archives
Community
Messageboard
List Servers
Mailing List
WebHosts
Consultants
Tech Jobs
15 Seconds
Home
Site Map
Press
Legal
Privacy Policy
internet.commerce














internet.com
IT
Developer
Internet News
Small Business
Personal Technology
International

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers

HardwareCentral
Compare products, prices, and stores at Hardware Central!

Creating Graphics On-The-Fly with ASP.NET
By Matt Duckhouse
Rating: 4.3 out of 5
Rate this article


  • email this article to a colleague
  • suggest an article

    Introduction/Overview

    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.

    You can download the source files used in the article, plus some additional examples, here.

    View a demo 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.

  • Rate This Article
    Not HelpfulMost Helpful
    1 2 3 4 5
    Other Articles
    Apr 21, 2005 - Building a FAQ Module for the ASP.NET Community Starter Kit
    This sample chapter from Packt Publishing's "Building Websites with the ASP.NET Community Starter Kit" illustrates how to build a new module on top of the existing code in the ASP.NET Community Starter Kit (CSK). Using a Frequently Asked Questions (FAQ) module as an example, it shows how creating a new module allows you to add entirely new features which integrate seamlessly with the rest of the framework.
    [Read This Article]  [Top]
    Oct 20, 2004 - Beyond the DataGrid: An Architectural View of the Data Source Model in ASP.NET 1.x and 2.0
    Dino Esposito discusses the differences between the DataGrid control in version 1.x and 2.0 of ASP.NET. In the process, he also builds an improved version of the 1.x control that can get you some of the new 2.0 features today.
    [Read This Article]  [Top]
    Aug 25, 2004 - Developing Web Parts with the ICellProvider Interface
    Most default SharePoint Server Web Parts can be connected across organizations. The second article in this series shows how to develop connectable Web Parts that provide information to other Web Parts.
    [Read This Article]  [Top]
    Aug 4, 2004 - Accessibility Improvements in ASP.NET 2.0 - Part 2
    Alex Homer continues to highlight some of the new ASP.NET 2.0 accessibility features. These features make it easier for visually impaired users to view and navigate Web sites and provide better support for alternative types of browsers and user agents.
    [Read This Article]  [Top]
    Jul 30, 2004 - Connectable Web Parts in SharePoint Portal Server 2003 - Part 1
    Most default SharePoint Server Web Parts can be connected across organizations. The first article in this series explains how to connect existing Web Parts using the connection Interface classes in the SharePoint architecture.
    [Read This Article]  [Top]
    Jul 27, 2004 - Accessibility Improvements in ASP.NET 2.0 - Part 1
    Alex Homer highlights some of the new ASP.NET 2.0 accessibility features. These features make it easier for visually impaired users to view and navigate Web sites and provide better support for alternative types of browsers and user agents.
    [Read This Article]  [Top]
    Jun 30, 2004 - Simplified and Extended Data Binding Syntax in ASP.NET 2.0
    Alex Homer discusses the simplification of, and extensions to, the ASP.NET 1.x data binding syntax, the new two-way data binding syntax for updating data sources, and the new syntax for binding to XML data in ASP.NET 2.0.
    [Read This Article]  [Top]
    May 18, 2004 - ASP.NET 2.0 Caching Features
    This article examines some of the new and exciting caching features in ASP.NET 2.0 and shows how to implement them in Web applications.
    [Read This Article]  [Top]
    May 11, 2004 - SharePoint Security and .NET Impersonation
    When implementing custom components that require access to restricted resources, implicit impersonation must be used. Jay Nathan shows how to create a class that makes using .NET Impersonation a snap.
    [Read This Article]  [Top]
    May 4, 2004 - Creating a Flexible Configuration Section Handler
    Jeff Gonzalez demonstrates how to create a flexible configuration section handler using C#. He provides a summary background of the .NET configuration system, explains why the system is useful, and shows how it can be extended.
    [Read This Article]  [Top]
    Mailing List
    Want to receive email when the next article is published? Just Click Here to sign up.

    Support the Active Server Industry



    JupiterOnlineMedia

    internet.comearthweb.comDevx.commediabistro.comGraphics.com

    Search:

    Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

    Jupitermedia Corporate Info


    Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

    Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

    Solutions
    Whitepapers and eBooks
    Microsoft Article: HyperV-The Killer Feature in WinServer ‘08
    Avaya Article: How to Feed Data into the Avaya Event Processor
    Microsoft Article: Install What You Need with Win Server ‘08
    HP eBook: Putting the Green into IT
    Whitepaper: HP Integrated Citrix XenServer for HP ProLiant Servers
    Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 1
    Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 2--The Future of Concurrency
    Avaya Article: Setting Up a SIP A/S Development Environment
    IBM Article: How Cool Is Your Data Center?
    Microsoft Article: Managing Virtual Machines with Microsoft System Center
    HP eBook: Storage Networking , Part 1
    Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
    MORE WHITEPAPERS, EBOOKS, AND ARTICLES
    Webcasts
    Intel Video: Are Multi-core Processors Here to Stay?
    On-Demand Webcast: Five Virtualization Trends to Watch
    HP Video: Page Cost Calculator
    Intel Video: APIs for Parallel Programming
    HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
    Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
    MORE WEBCASTS, PODCASTS, AND VIDEOS
    Downloads and eKits
    Sun Download: Solaris 8 Migration Assistant
    Sybase Download: SQL Anywhere Developer Edition
    Red Gate Download: SQL Backup Pro and free DBA Best Practices eBook
    Red Gate Download: SQL Compare Pro 6
    Iron Speed Designer Application Generator
    MORE DOWNLOADS, EKITS, AND FREE TRIALS
    Tutorials and Demos
    How-to-Article: Preparing for Hyper-Threading Technology and Dual Core Technology
    eTouch PDF: Conquering the Tyranny of E-Mail and Word Processors
    IBM Article: Collaborating in the High-Performance Workplace
    HP Demo: StorageWorks EVA4400
    Intel Featured Algorhythm: Intel Threading Building Blocks--The Pipeline Class
    Microsoft How-to Article: Get Going with Silverlight and Windows Live
    MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES