Before the advent of the .NET framework, creating images on the fly for a web
browser was a tedious task. Now, thanks to the .Net framework, creating images
on the fly is a simple task. This article will provide the reader with the fundamentals
necessary to start developing dynamic images with the .Net framework.
Creating dynamic images with the .Net framework is a four-step process. First,
set the content-type of the aspx file to an image type. Second, get an instance
of the Graphics object from a Bitmap. Third, draw on the Graphics object. Four,
save the Bitmap to an output stream.
The default content-type value for an aspx file is "text/html
".
If we want to output an image, say an GIF, we need to set the content-type to
"image/gif
". We simply add the following to the top of
our aspx page.
<%@ Page ContentType = "image/gif"%>
Drawing the graphics
Next we want to get an instance of the Graphics object so we can start drawing our image. We first need to create a Bitmap with a specified dimension and then use this Bitmap to get an instance of the Graphics object.
Dim objBitmap As Bitmap
Dim objGraphics As Graphics
objBitmap = New Bitmap(200, 200)
objGraphics = Graphics.FromImage(objBitmap)
Now that we have an instance of the Graphics object, we can start drawing our image. To draw a line diagonally across our Graphics object, we use the DrawLine method. We pass a Pen object as well as the start and end points of the line. The Pen object specifies the width, color, line style and other attributes of the line.
objGraphics.DrawLine(new Pen(Color.Red), 0, 0, 200, 200)
When we are finished drawing the image we must save the Bitmap to an output stream. Since we want to send the image to a web browser we save the Bitmap to the Http output stream and specify the image type we want to send it back as.
objBitmap.Save(Response.OutputStream, ImageFormat.Gif)
To help the garbage collector we dispose of the Bitmap and the Graphics object.
objBitmap.Dispose()
objGraphics.Dispose()
Putting all the code together our aspx file would look like this.
<%@ Page ContentType = "image/gif"%>
<%@ Import Namespace = "System.Drawing" %>
<%@ Import Namespace = "System.Drawing.Imaging" %>
<Script Runat = "Server">
Sub Page_Load
Dim objBitmap As Bitmap
Dim objGraphics As Graphics
objBitmap = New Bitmap(200, 200)
objGraphics = Graphics.FromImage(objBitmap)
objGraphics.DrawLine(new Pen(Color.Red), 0, 0, 200, 200)
objBitmap.Save(Response.OutputStream, ImageFormat.Gif)
objBitmap.Dispose()
objGraphics.Dispose()
End Sub
</Script>
Although this is a very simple example, it illustrates the steps necessary
to create an image on the fly using the .Net framework. In my next article I
will show how we can use this method to develop a graph.
Comments