Generate image On the fly using ASP.NET

1 minute read

Generating image on the fly is not difficult in asp.net. Here I have created national flag of Bangladesh on the fly and displayed this as JPEG image format in asp.net web form. So let’s start to draw an image on the fly.

Step 1: Add a new web form in ASP.net website.

Step 2: In the Page_Load of the web form write the following code

protected void Page_Load(object sender, EventArgs e)
{
        //Define the rectangle with (x co-ordinate, y co-ordinate, width, height)
        RectangleF rectF = new RectangleF(0, 0, 400, 200);
        Bitmap img = new Bitmap(400, 200, PixelFormat.Format24bppRgb);
        Graphics grphs = Graphics.FromImage(img);
        SolidBrush bgBrush = new SolidBrush(System.Drawing.Color.Green);
        
        grphs.FillRectangle(bgBrush, rectF);
        
        SolidBrush elpsBgBrush = new SolidBrush(System.Drawing.Color.Red);
        
        //Fill the interior of an ellipse by the pair of co-ordinates and height and width
        grphs.FillEllipse(elpsBgBrush, 140, 40, 130, 130);
        
        int fontSize = 20;
        string fontName = "Arial" + ".ttf";
        PrivateFontCollection privateFontCollection = new PrivateFontCollection();
        privateFontCollection.AddFontFile(@"C:/WINDOWS/Fonts/" + fontName);
        
        FontFamily fontFamily = privateFontCollection.Families[0];
        
        // Set font style
        int fontStyle = Convert.ToInt32(Request.Form.Get("fontstyle"));
        string text = "Bangladesh";
        
        SolidBrush fgBrush = new SolidBrush(System.Drawing.Color.Yellow);
        FontStyle style = FontStyle.Bold;
        
        StringFormat format = new StringFormat();
        format.FormatFlags = StringFormatFlags.DirectionRightToLeft;
        
        Font font = new Font(fontFamily, fontSize, style, GraphicsUnit.Pixel);
        
        grphs.DrawString(text, font, fgBrush, rectF, format);
        
        Response.ContentType = "image/jpeg";
        img.Save(Response.OutputStream, ImageFormat.Jpeg);
        
        // Dispose objects
        img.Dispose();
}

Here RectangleF stores a set of four floating-point numbers that represent the location and size of a rectangle. Here first pair is (x,y) co-ordinate and second pair is width and height. SolidBrush define a brush of single color. FillRectangle and FillEllipse is responsible for both Filling rectangle and Ellipse. Graphics.DrawString is used to draw text in the rectangle.

Now run the website. Yes! You have drawn your desired National Flag of Bangladesh and its look like this.

Output: