Generate image on the fly by ASP.NET

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

Step 1: Add a new web form in 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

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.


National Flag bangladesh

Please share, if it is helpfulShare on FacebookShare on LinkedInTweet about this on TwitterShare on Google+Email this to someonePrint this page

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>