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.
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:
- Use the library to create any image. We may load an image from any stream (file, DB or any other place).
- Set the response type to an image of the required type (GIF, JPEG, BMP…).
Response.Write the image binary stream hence pushing this image to the client.
Let's jump into the code as there is not much to talk about here.
The first thing we do is initialize the
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";
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
- 10th July, 2010: Initial post