Dynamically create gradient image

The code below dynamically creates a jpeg with a gradient, saves it to the server, and is assigned to an image object. I used the code below to dynamically generate a bar graph. The reason we append the uniqueVal to the file name is so that if the user is constantly refreshing the graph, the browser won’t pull up a cached image.

using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Drawing;

string uniqueVal = DateTime.Now.Ticks.ToString();
Bitmap bitmap = new Bitmap(180, 15);
Graphics graphics = Graphics.FromImage(bitmap);
LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0,0,180,15), Color.Gainsboro, Color.Blue, 45.0f, false);
graphics.FillRectangle(brush, new Rectangle(0, 0, 180, 15));
string fileName = "gradient" + uniqueVal + ".jpg";
bitmap.Save(Server.MapPath(fileName), ImageFormat.Jpeg);
graphics.Dispose();
bitmap.Dispose();
System.Web.UI.WebControls.Image img = new System.Web.UI.WebControls.Image();
img.ImageUrl = Server.MapPath(fileName);

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s