Click here to Skip to main content
11,436,156 members (62,382 online)
Click here to Skip to main content

Web Graphics On The Fly in ASP.NET

, 25 Nov 2002
Rate this:
Please Sign up or sign in to vote.
Create web graphics on the fly with the ASP.NET quickly.
<!-- Download Links --> <!-- Article image -->

Sample Image - ASP.NET_Web_Graphics.jpg

<!-- Add the rest of your HTML here -->

Introduction

We all know what it is like when it comes to creating graphics for the web. Mind you, I find this to be a very tedious job, in fact many times I will try to avoid it. There have been other ways to create graphics on the fly, in fact you may wish to read an article written on VML posted here at The Code Project.

While there is nothing wrong using this or any other method available we all know the future ( at least in Microsoft’s eyes) is .NET. With that said, I would like to show you a method for creating dynamic graphics for the web in ASP.NET. Keep in mind that all of the following code will be done in VB.NET & C# as well.

To Begin

The use of namespaces is vital in the .NET environment. We must import the proper namespaces to allow us to access the methods and properties we call in the following code below. I have updated this article to include the C# version of the code, you will notice how very similar they are.

‘=====================================
‘Include All Pertinent Namespaces Here
‘=====================================

<%@ Page Language="VB" ContentType="image/jpeg" %>
<%@ Import Namespace="System.Drawing" %>
<%@ Import Namespace="System.Drawing.Text" %>
<%@ Import Namespace="System.Drawing.Imaging" %>
<%@ Import Namespace="System.Drawing.Drawing2D" %>

	<%

	Response.Clear( )
	Dim height As Integer = 100
	Dim width As Integer = 200
	Dim r As New Random
	Dim x  As Integer = r.Next(75)

	Dim bmp As new Bitmap(width, height, PixelFormat.Format24bppRgb)
	Dim g as Graphics = Graphics.FromImage(bmp)
	
	g.TextRenderingHint = TextRenderingHint.AntiAlias
	g.Clear(Color.Orange)
	g.DrawRectangle(Pens.White, 1, 1, width-3, height-3)
	g.DrawRectangle(Pens.Gray, 2, 2, width-3, height-3)
	g.DrawRectangle(Pens.Black, 0, 0, width, height)
	g.DrawString("The Code Project", _
			New Font("Arial", 12, FontStyle.italic), _
			SystemBrushes.WindowText, New PointF(x,50))


	bmp.Save(Response.OutputStream, ImageFormat.Jpeg)
	g.Dispose( )
	bmp.Dispose( )
	Response.End( )
	
	%>

C# Version

<%@ Page Language="C#" ContentType="image/jpeg" %>
<%@ Import Namespace="System.Drawing" %>
<%@ Import Namespace="System.Drawing.Text" %>
<%@ Import Namespace="System.Drawing.Imaging" %>
<%@ Import Namespace="System.Drawing.Drawing2D" %>

	<%

	Response.Clear();
	int height = 100;
	int width = 200;
	Random r = new Random();
	int x = r.Next(75);

	Bitmap bmp = new Bitmap(width, height, PixelFormat.Format24bppRgb);
	Graphics g = Graphics.FromImage(bmp);
	
	g.TextRenderingHint = TextRenderingHint.AntiAlias;
	g.Clear(Color.Orange);
	g.DrawRectangle(Pens.White, 1, 1, width-3, height-3);
	g.DrawRectangle(Pens.Gray, 2, 2, width-3, height-3);
	g.DrawRectangle(Pens.Black, 0, 0, width, height);
	g.DrawString("The Code Project", new Font("Arial", 12, FontStyle.Italic), 
	SystemBrushes.WindowText, new PointF(x,50) );

	bmp.Save(Response.OutputStream, ImageFormat.Jpeg);
	g.Dispose();
	bmp.Dispose();
	Response.End();
	
	%>

Code Explanation

While there is not a lot to this code I would like to explain what is going on here. To begin we clear the Response object. The variables height and width are defined as the dimensions of our image, you can adjust as you wish or create a subroutine where you pass these values in. So far this is rather rudimentary, nothing extremely extensive so far. Next we will declare a variable r to be of type Random. The integer variable x on the next line is assigned a random value using r with a seed value of 75, you can use whatever seed value you would like.

The next two objects that we create will be new for any ASP web developers. First we are to create a new Bitmap object, this item will define the area to which we are doing our drawing on. There are three arguments that are passed to it, the width and height of our image and the pixel format. There are a series of different pixel formats to choose from, here is a detailed explanation of the different types available to you.

Next we will use the graphics object to set the TextRenderingHint to TextRenderingHint.AntiAlias. This allow us to take advantage of antialiasing characteristics when displaying fonts. Antialiasing allows you to get ride of jagged lines in your text by blending shades of gray or color around the text to make it appear smoother.

On the next line we are actually setting the main color of our bitmap image. I choose Code Project orange for this example Smile | :) . In the next three lines we are actually going to begin drawing on our image. The method that gets called is the same, only changing a few of the parameters. We are actually just drawing a framework at the edge of the image. Essentially you can see that by the points being specified in the arguments list. Here is a breakdown of how the DrawRectangle works; keep in mind the x and y coordinates are in terms of the upper left hand corner:

g.DrawRectangle( [Pen],[x],[y],[width],[height] )	
Next we will actually draw some text onto our Bitmap object. The DrawString method is overloaded and takes a series of arguments that are specified like this for my example:
g.DrawString( [String],[Font], <Brush>,[PointF] )
For the first time we will go ahead and make a direct method call using the Bitmap object. The method to save our bitmap is simply Save which is overloaded (big surprise) passing the outputstream object and image format. Here is another list of options you have in regards to your image format.

There have been questions regarding the next two lines of code, I am calling the Dispose method for both the Graphics object and Bitmap object that we created. Even though .NET development can manage our object(s) with respect to garbage collection, it is always a good idea to clear these items when you know you are done with them. You can exclude these two calls and garbage collection will still take place, it's your call.

Conclusion

That’s all it takes to create dynamic graphics through the use of code alone.

Other Articles

Article on MSDN entitled: Create Snazzy Web Charts and Graphics On the Fly with the .NET Framework.

Update History

  • February 13th, 2002 - Original article is posted.
  • July 18th, 2002 - Updated to include code explanation section.
  • November 25th, 2002 - Updated to include C# code example.
  • November 26th, 2002 - Updated to allow AntiAlias to work properly thanks to leppie.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

Nick Parker
Software Developer (Senior)
United States United States
Nick graduated from Iowa State University with a B.S. in Management Information System and a minor in Computer Science. Nick works for Zetetic.

Nick has also been involved with the Iowa .NET User Group since it's inception, in particular giving presentations over various .NET topics. Nick was awarded the Visual C# MVP award from Microsoft for four years in a row.

In his mystical spare time he is working on a development project called "DeveloperNotes" which integrates into Visual Studio .NET allowing developers easy access to common code pieces. He is also a fan of using dynamically typed languages to perform unit testing, not to mention how he loves to talk about himself in the third person.

Comments and Discussions

 
GeneralMy vote of 3 Pin
sharadKamalakarshitole3-Apr-14 0:08
membersharadKamalakarshitole3-Apr-14 0:08 
Question588KB or 588B? Pin
Dolary12-Sep-06 22:07
memberDolary12-Sep-06 22:07 
QuestionValidation: Element 'html' occurs too few times. Pin
ThaNerd16-Nov-05 9:58
memberThaNerd16-Nov-05 9:58 
AnswerRe: Validation: Element 'html' occurs too few times. Pin
Heywood Jablowme23-Jan-06 18:27
memberHeywood Jablowme23-Jan-06 18:27 
QuestionCan this code write as a Custom Control Pin
yovio8-Jan-04 23:19
memberyovio8-Jan-04 23:19 
AnswerRe: Can this code write as a Custom Control Pin
Nick Parker10-Jan-04 4:15
editorNick Parker10-Jan-04 4:15 
GeneralGraphics as part of page Pin
Andre van der Graaf20-Dec-02 10:12
memberAndre van der Graaf20-Dec-02 10:12 
GeneralRe: Graphics as part of page Pin
Nick Parker20-Dec-02 10:16
editorNick Parker20-Dec-02 10:16 
GeneralRe: Graphics as part of page Pin
Heath Stewart18-Jan-03 22:44
memberHeath Stewart18-Jan-03 22:44 
GeneralRe: Graphics as part of page Pin
Andre van der Graaf22-Jan-03 9:41
memberAndre van der Graaf22-Jan-03 9:41 
GeneralRe: Graphics as part of page Pin
roze_love14-Sep-04 4:37
memberroze_love14-Sep-04 4:37 
Questioncode rendering on the .aspx page!? Pin
cronosxfiles30-Nov-02 13:39
membercronosxfiles30-Nov-02 13:39 
AnswerRe: code rendering on the .aspx page!? Pin
Nick Parker1-Dec-02 17:45
editorNick Parker1-Dec-02 17:45 
GeneralRe: Compilation errors :( Pin
cronosxfiles9-Dec-02 5:21
membercronosxfiles9-Dec-02 5:21 
GeneralRe: Compilation errors :( Pin
Nick Parker9-Dec-02 9:12
editorNick Parker9-Dec-02 9:12 
GeneralRe: Compilation errors :( Pin
cronosxfiles9-Dec-02 13:42
membercronosxfiles9-Dec-02 13:42 
GeneralCross Selling Pin
SimonS25-Nov-02 21:44
memberSimonS25-Nov-02 21:44 
GeneralRe: Cross Selling Pin
Nick Parker26-Nov-02 2:13
editorNick Parker26-Nov-02 2:13 
GeneralUsing a templated background image Pin
leppie10-Nov-02 5:39
memberleppie10-Nov-02 5:39 
GeneralRe: Using a templated background image Pin
Nick Parker11-Nov-02 9:38
editorNick Parker11-Nov-02 9:38 
GeneralRe: Using a templated background image Pin
leppie11-Nov-02 9:57
memberleppie11-Nov-02 9:57 
GeneralRe: Using a templated background image Pin
Nick Parker11-Nov-02 10:07
editorNick Parker11-Nov-02 10:07 
GeneralRe: Using a templated background image Pin
leppie11-Nov-02 11:16
memberleppie11-Nov-02 11:16 
GeneralRe: Using a templated background image Pin
leppie26-Nov-02 10:59
memberleppie26-Nov-02 10:59 
GeneralRe: Using a templated background image Pin
Nick Parker26-Nov-02 12:24
editorNick Parker26-Nov-02 12:24 
GeneralRe: Using a templated background image Pin
Nick Parker26-Nov-02 13:45
editorNick Parker26-Nov-02 13:45 
GeneralRe: Using a templated background image Pin
leppie30-Nov-02 11:19
memberleppie30-Nov-02 11:19 
GeneralRe: Using a templated background image Pin
Nick Parker30-Nov-02 13:00
editorNick Parker30-Nov-02 13:00 
GeneralRe: Using a templated background image Pin
leppie30-Nov-02 13:13
memberleppie30-Nov-02 13:13 
GeneralCool article Pin
Jon Sagara28-Oct-02 20:14
memberJon Sagara28-Oct-02 20:14 
GeneralRe: Cool article Pin
Nick Parker29-Oct-02 2:06
memberNick Parker29-Oct-02 2:06 
GeneralJScript.NET version here. Pin
Anonymous22-Aug-02 9:21
sussAnonymous22-Aug-02 9:21 
GeneralRe: JScript.NET version here. Pin
Nick Parker22-Aug-02 9:41
memberNick Parker22-Aug-02 9:41 
QuestionDispose? Pin
Jörgen Sigvardsson14-Feb-02 8:17
memberJörgen Sigvardsson14-Feb-02 8:17 
AnswerRe: Dispose? Pin
Nick Parker14-Feb-02 18:28
memberNick Parker14-Feb-02 18:28 
AnswerRe: Dispose? Pin
Christian Tratz19-Feb-02 0:08
memberChristian Tratz19-Feb-02 0:08 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150428.2 | Last Updated 26 Nov 2002
Article Copyright 2002 by Nick Parker
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid