Click here to Skip to main content
Email Password   helpLost your password?

Sample Image - ASP.NET_Web_Graphics.jpg

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 :). 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], ,[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

You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
Question588KB or 588B?
Dolary
22:07 12 Sep '06  
When i download the 'code.zip',it shows only 588B bytes!

There is only one page named 'graphics.aspx' in the 'code.zip'.

How can i download the whole source files?

QuestionValidation: Element 'html' occurs too few times.
ThaNerd
9:58 16 Nov '05  
It may sound as a newbie's question, and there is a reason to this: I'm an actual newbie with ASP. I spent the last 5 years doing such things with PHP and Apache.

Now that i gracefully and licencefully received a copy of both Visual Studio 2005 and SQL Server 2005, i want to try them both and play with them.

Now, i just created a new website project, created a directory, added an empty ASPX file, and pasted your code as the whole content of the file. Now when i want to "publish" the website, it won't let me, because of the error stated in the title. How can i come around this?

Life would be so much easier if we could look at the source code...
AnswerRe: Validation: Element 'html' occurs too few times.
Heywood Jablowme
18:27 23 Jan '06  
disable validation in Tools | Options | Text Editor | HTML | Validation.
GeneralCan this code write as a Custom Control
yovio
23:19 8 Jan '04  
Can this idea write become a custom control that we can compile it become a Web Control ?

I've been trying but cannot find the idea how?

But, I know there is a company that make A custom Control for On The Fly Image, but I forgot the name of the control
GeneralRe: Can this code write as a Custom Control
Nick Parker
4:15 10 Jan '04  
yovio wrote: Can this idea write become a custom control that we can compile it become a Web Control ?
Yes


yovio wrote: I've been trying but cannot find the idea how?
Check MSDN[^], or post a specific question in the forums or on an article if you get stuck somewhere.

- Nick Parker
  My Blog

GeneralGraphics as part of page
Andre van der Graaf
10:12 20 Dec '02  
Great article Nick! The ideas are very clearly explained.

However, sofar I'm not able to generate a graphic on the fly which are then part of a page containing other items e.g. plain text.

I mean, if the 'on the fly' code is embedded in html, all this html seems to be ignored.

Does anyone know how to do something like this:

BlahBlah
Graphic on the fly
BlahBlah

That would be great!

Best Regards,
André
GeneralRe: Graphics as part of page
Nick Parker
10:16 20 Dec '02  
Andre van der Graaf wrote: I mean, if the 'on the fly' code is embedded in html, all this html seems to be ignored.
Thanks for the comments. Smile I will check into this when I get home, should be able to get something out for you. Thanks again.


Nick Parker

You see the Standards change. - Fellow co-worker


GeneralRe: Graphics as part of page
Heath Stewart
22:44 18 Jan '03  
All you have to do is include an <img> tag like usual, href'ing an ASP.NET handled file (I recommend using a .ashx file as opposed to a .aspx file because there's less overhead but the actually programming language is still the same (.ashx just isn't a container for HTML, etc.)):
BlahBlah
<img href="/modules/imgGen.ashx?text=blah%20blah&alpha=true"> BlahBlah
Simple as that.

"Well, I wouldn't say I've been missing it, Bob." - Peter Gibbons
GeneralRe: Graphics as part of page
Andre van der Graaf
9:41 22 Jan '03  
Yeah, that works!

Thanks a lot.
GeneralRe: Graphics as part of page
roze_love
4:37 14 Sep '04  
Thanks very very much for your reply.
"Payam Mahmoudi"
Generalcode rendering on the .aspx page!?
cronosxfiles
13:39 30 Nov '02  
Hello:

I'm very new to .NET I just read that you can't render instructions indide the HTML code like on the .asp pages. Then, how come that all the demo code in this article is rendered on the page with the classic <% %> tags, instead of being functions inside <script runat="server"></script> tags? OMG
I was looking a demo code like this. But, how can I have the BitMap saved to a file? Like replacing Response.OutputStream for some fileObj variable.

Thanks in advance for any hint.

_.,-*~'`^`'~*-,._.,-*~'`^`'~*-,._.,-*~'`^`
Juan Manuel Gómez Ramos
B.Sc. Computer Science
eMail: eFax:+1-707-313-0329 (USA) +44-870-125-4936 (UK)
http://chronos.itgo.com
^`'~*-,._.,-*~'`^`'~*-,._.,-*~'`^`'~*-,._
GeneralRe: code rendering on the .aspx page!?
Nick Parker
17:45 1 Dec '02  
cronosxfiles wrote: how come that all the demo code in this article is rendered on the page with the classic <% %> tags, instead of being functions inside <script runat="server"></script> tags?
If you look carefully at the code, the first section adds a header to the HTTP response telling it what type is being returned (e.g.,ContentType="image/jpeg"). The <% %> tags are still supported, however you could have just as easily wrapped this into a function, however that really wasn't the scope of this article. You can't do this alone in ASP (version 3.0) without creating a COM object that wraps a lot of GDI code internally, that is what makes the .NET Framework so nice. Hope this helps some. Smile


Nick Parker
GeneralRe: Compilation errors :(
cronosxfiles
5:21 9 Dec '02  
Hello Nick:

This might be out-of-topic. If you could tell me were to post .Net compilation errors related questions, I'd be grateful. Unsure I just installed .Net SDK and the .NetSP2. Typed your C# code example with Notepad and saved as a .aspx page. When I tried with the browser, I received this error:
========================================================================
Server Error in '/testsite' Application. --------------------------------------------------------------------------------

Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

Compiler Error Message: CS1595: 'System.Collections.ArrayList' is defined in multiple places; using definition from 'C:\winnt\microsoft.net\framework\v1.0.3705\mscorlib.dll'

Source Error:



Line 49: private static bool __intialized = false;
Line 50:
Line 51: private static System.Collections.ArrayList __fileDependencies;
Line 52:
Line 53: public bmpSave_aspx() {


Source File: C:\WINNT\Microsoft.NET\Framework\v1.0.3705\Temporary ASP.NET Files\testsite\29dafa64\9b4d9e5c\mwsj-thi.0.cs Line: 51


========================================================================

the line "private static System.Collections.ArrayList __fileDependencies;
" is shown in red. As is not part of my/your code, I suppose the error comes from the Compiler. Is the second time I install .Net Framework. Don't know what could be the problem Confused Thanks in advance for any hint.

_.,-*~'`^`'~*-,._.,-*~'`^`'~*-,._.,-*~'`^`
Juan Manuel Gómez Ramos
B.Sc. Computer Science
eMail: eFax:+1-707-313-0329 (USA) +44-870-125-4936 (UK)
http://chronos.itgo.com
^`'~*-,._.,-*~'`^`'~*-,._.,-*~'`^`'~*-,._
GeneralRe: Compilation errors :(
Nick Parker
9:12 9 Dec '02  
cronosxfiles wrote: Don't know what could be the problem
Sure do, it is an issue with the compiler not having the correct permissions to access mscorlib.dll. Refer to Microsoft Knowledge Base Article - 318274[^] for full details. You should be able to resolve this by granting "List Folder/Read Data" permissions to the ASPNET account. Smile


Nick Parker

Not everything that can be counted counts, and not everything that counts can be counted. - Albert Einstein


GeneralRe: Compilation errors :(
cronosxfiles
13:42 9 Dec '02  
Thanks a lot Nick! I finally could see my first ASP.Net app working? Big Grin I think they should have had one of the two options set by default.

Regards, Juanma.

_.,-*~'`^`'~*-,._.,-*~'`^`'~*-,._.,-*~'`^`
Juan Manuel Gómez Ramos
B.Sc. Computer Science
eMail: eFax:+1-707-313-0329 (USA) +44-870-125-4936 (UK)
http://chronos.itgo.com
^`'~*-,._.,-*~'`^`'~*-,._.,-*~'`^`'~*-,._
GeneralCross Selling
SimonS
21:44 25 Nov '02  
Hi Nick

Thanks for linking to my VML article. Roll eyes

This might (doubt it) actually motivate me into writing some SVG articles before Chris G. does!

Thanks again.

Cheers,
Simon

"From now on, if rogue states want to buy weapons of mass destruction, they're going to have to go on eBay," Mr. Bezos said.

GeneralRe: Cross Selling
Nick Parker
2:13 26 Nov '02  
SimonS wrote: Thanks for linking to my VML article.
No Problem Simon, thanks for writing the VML article. Smile


SimonS wrote: This might (doubt it) actually motivate me into writing some SVG articles before Chris G. does!
Write one, I would be interested in reading it. Wink



Nick Parker
May your glass be ever full.
May the roof over your head be always strong.
And may you be in heaven half an hour before the devil knows you’re dead. - Irish Blessing


GeneralUsing a templated background image
leppie
5:39 10 Nov '02  
Hi Nick

Nice article, was trying to do this a while back and didnt know about this, maybe the VB filter Poke tongue

I was wonder how to open a "template" type gif/jpeg from the server, so I could apply some editing on it and then save it back a named image...

Any ideas?



"I dont have a life, I have a program."
GeneralRe: Using a templated background image
Nick Parker
9:38 11 Nov '02  
leppie wrote: I was wonder how to open a "template" type gif/jpeg from the server, so I could apply some editing on it and then save it back a named image...
I would assume you are doing this on a Windows based application and not through the web?

Nick Parker
May your glass be ever full.
May the roof over your head be always strong.
And may you be in heaven half an hour before the devil knows you’re dead. - Irish Blessing


GeneralRe: Using a templated background image
leppie
9:57 11 Nov '02  
Nick Parker wrote: I would assume you are doing this on a Windows based application and not through the web?
Nope ASP.NET , but I found the answer Smile

1. asp_wp must have write rights in the directory
2. some code in C# Smile

public static string GetPictureUrl(string userid, string path)
{
//must add some code to prevent regeneration
Bitmap template = (Bitmap) Bitmap.FromFile(path + "template.bmp");
Graphics g = Graphics.FromImage(template);
//not g.SmoothingMode!!! doesnt work for text!
g.TextRenderingHint = TextRenderingHint.AntiAlias;
g.DrawString("The Code Project", new Font("Impact", 14, FontStyle.Bold),
SystemBrushes.WindowText,
new Point(2, 2));
string filename = path + @"userimages\" + userid + ".jpeg";
SaveJPGWithCompressionSetting(template, filename, 90);
g.Dispose();
template.Dispose();
return "./userimages/" + userid + ".jpeg";
}

//the following is some code I found on dotnet247 from some MS guy :)
private static void SaveJPGWithCompressionSetting( Image image, string szFileName, long lCompression )
{
EncoderParameters eps = new EncoderParameters(1);
eps.Param[0] = new EncoderParameter( Encoder.Quality, lCompression );
ImageCodecInfo ici = GetEncoderInfo("image/jpeg");
image.Save( szFileName, ici, eps );
}

private static ImageCodecInfo GetEncoderInfo(String mimeType)
{
int j;
ImageCodecInfo[] encoders;
encoders = ImageCodecInfo.GetImageEncoders();
for(j = 0; j < encoders.Length; ++j)
{
if(encoders[j].MimeType == mimeType)
return encoders[j];
} return null;
}

Cheers Smile

"I dont have a life, I have a program."
GeneralRe: Using a templated background image
Nick Parker
10:07 11 Nov '02  
leppie wrote: Nope ASP.NET , but I found the answer
Hmmm, looks nice, however are going to "edit" a picture on the web?? Confused

Nick Parker
May your glass be ever full.
May the roof over your head be always strong.
And may you be in heaven half an hour before the devil knows you’re dead. - Irish Blessing


GeneralRe: Using a templated background image
leppie
11:16 11 Nov '02  
Nick Parker wrote: Hmmm, looks nice, however are going to "edit" a picture on the web??
who ever or how ever? Poke tongue

I think this is the answer you are looking for though. Basically I would create a JPEG for each user, say when they register, then in the webpage it would be displayed. I do however have a problem that I'm not sure how fast 1 JPEG file in say a directory of 20000 JPEG's (users) will be "found" and read...also the size could be a problem. 20000 x 3kb = 60mb Eek!

The reason why I wanted to do this is because of the retarded performance of the Image.Save method so I could save a bit by not having to regenerate the files but rather save them to disk and use that as future reference (as the code suggests)

Cheers Smile

"I dont have a life, I have a program."
GeneralRe: Using a templated background image
leppie
10:59 26 Nov '02  
Hi Nick

Nice to see C# version, but you still have not taken my advice:

//not g.SmoothingMode!!! doesnt work for text!   
g.TextRenderingHint = TextRenderingHint.AntiAlias;
Just a reminder Poke tongue

DBHelper - SQL Stored Procedure Wrapper & Typed DataSet Generator for .NET popularity better now, thank you Smile
GeneralRe: Using a templated background image
Nick Parker
12:24 26 Nov '02  
leppie wrote: //not g.SmoothingMode!!! doesnt work for text!
g.TextRenderingHint = TextRenderingHint.AntiAlias;

I'll take a look at it when I get home, thanks. Smile

Nick Parker
May your glass be ever full.
May the roof over your head be always strong.
And may you be in heaven half an hour before the devil knows you’re dead. - Irish Blessing


GeneralRe: Using a templated background image
Nick Parker
13:45 26 Nov '02  
leppie wrote: but you still have not taken my advice
Fixed, advice taken and noted. Thanks Smile

Nick Parker
May your glass be ever full.
May the roof over your head be always strong.
And may you be in heaven half an hour before the devil knows you’re dead. - Irish Blessing



Last Updated 26 Nov 2002 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010