Generating an article rating image

You may have noticed a couple of new icons at the top right of each article?  The first new icon shows 5 grey stars, these fill up as gold stars as people specifying a rating when they comment on an article (the second new icon).  I thought I'd share the source code which generates this image.

The first thing to do is to have an <img> tag in your source code which looks something like this

<img alt="Rating"
  src='/ArticleRatingImage.aspx?rating=<%# DataBinder.Eval(Article, "AverageRating") %>'
>

Rather than linking directly to an image URL this <img> references an ASPX page with a single parameter, "rating=x", where "x" is the AverageRating property of an Article property of the current page.

Generating the image

First I created an image which consisted of 10 stars, the first 5 were grey, and the last 5 were gold.

The Page_Load code of the ArticleRatingImage.aspx page looks like this.

string fileName = Server.MapPath("/Images") + "\\ArticleRating.gif";
Image starImage = Image.FromFile(fileName);
int halfOriginalWidth = starImage.Width / 2;
Bitmap ratingImage = new Bitmap(halfOriginalWidth, starImage.Height);
Graphics ratingCanvas = Graphics.FromImage(ratingImage);

//Draw the grey background stars
SolidBrush purpleBrush = new SolidBrush(Color.White);
ratingCanvas.FillRectangle(purpleBrush, 0, 0, ratingImage.Width, ratingImage.Height);
ratingCanvas.DrawImage(starImage, 0, 0);

//Calculate the size of the gold stars
double rating = 0;
if (Request.QueryString["rating"] != null)
try
{
    rating = Convert.ToDouble(Request.QueryString["rating"]);
    if (rating < 0)
        rating = 0;
    else
    if (rating > 5)
        rating = 5;
}
catch
{
}

int newWidth = (int)System.Math.Round(halfOriginalWidth * rating / 5);
Rectangle sourceRect = new Rectangle(halfOriginalWidth, 0, newWidth, starImage.Height);
Rectangle destRect = new Rectangle(0, 0, newWidth, starImage.Height);

//Draw the gold stars
ratingCanvas.DrawImage(starImage, destRect, sourceRect, GraphicsUnit.Pixel);

Response.ContentType = "image/gif";
ratingImage.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif);


Conclusion

This was not a very difficult effect to achieve, however, it does not seem possible to create a GIF in .net which has a transparent background, at least not using the standard framework.

If anyone knows how to create a gif at runtime with a transparent background I would like to hear how to do it.

 

Share this article!

Follow us!

Find more helpful articles: