Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

ASP.NET Generating Images on the Fly

0.00/5 (No votes)
9 Jul 2010 1  
This article is a very quick description around how to generate images on the fly for an ASP.NET web application.

Introduction

In Windows applications, the graphic’s library can help us generate images. Similar techniques can be applied to web applications. In this article, we explore these techniques.

At times, we need to create graphs and charts or some sort of image or may be add a water mark / copyright notice and so on.

Until HTML 5 is around and we have the canvas tag supported, this technique can help you to create images for a web application on the fly.

Audience

The audiences of this article are expected to know about .NET, Graphics library and the concept of HTTP handler.

The Basic Idea

The basic idea is very simple:

  1. Use the library to create any image. We may load an image from any stream (file, DB or any other place).
  2. Set the response type to an image of the required type (GIF, JPEG, BMP…).
  3. Response.Write the image binary stream hence pushing this image to the client.

The Code

Let's jump into the code as there is not much to talk about here.

The first thing we do is initialize the Graphics classes:

Bitmap bitMap = new Bitmap(300, 200); 
Graphics graphics = Graphics.FromImage(bitMap); 

Then we start to do some drawings inside it. For this example, we make the background golden and add a circle, a square, lines and curves.

SolidBrush solidWhiteBrush = new SolidBrush(Color.Gold); 
graphics.FillRectangle(solidWhiteBrush, 0, 0, 300, 200); 
graphics.FillEllipse(new LinearGradientBrush(new Rectangle(0, 100, 50, 50), 
	Color.Plum, Color.Red, 20), 0, 100, 50, 50); 
graphics.DrawLine(new Pen(Color.Black), 50, 125, 100, 125); 
graphics.FillRectangle(new SolidBrush(Color.Purple), 100, 100, 50, 50); 
graphics.DrawBezier(new Pen(Color.RoyalBlue), 100, 70, 200, 80, 70, 250, 200, 200); 

Finally, we write this image as a binary data to the stream. It should be noted that the content type is image/giv and the Save is being done onto a stream as a GIF.

Response.ContentType = "image/gif"; 
bitMap.Save(Response.OutputStream, ImageFormat.Gif); 
Image.png

How Will I Make it Work in a Real Application?

In a real world application, this code should be written in an HTTP handler while the image is displayed in an img tag.

History

  • 10th July, 2010: Initial post

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