Geeks With Blogs


Locations of visitors to this page

View ► Sanjay Uttam []'s profile on LinkedIn

Add to Google Reader or Homepage

Sanjay Uttam Predominantly .NET

Was doing my daily research today and learned a couple of new and interesting things.  A while back, I wrote a post about rendering options using .NET 3.5 SP1's charting component.  I outlined a few of the more conventional/out-of-the-box methods (temporary directory, binary streaming).  I also outlined a lesser-known technique in which you stream binary data to the src attribute of your <img> tag.  That ends up looking like this...

<img src='data:image/png;base64, iVBORw0KGgoAAAA[snip]; />

The full post can be found here.

In any case, it turns out you can apply a similar/identical technique to your CSS for a performance gain (by way of reducing HTTP requests)....It's really the same exact technique as above.  So, for example, a CSS class may look like this:

#some-css-class{background-image:url(data:image/png;base64,iVBORw0KGgoAAAA [snip] )}

This can be very useful for sites that have a large number of image paths embedded in CSS.  But "How do I convert my existing images?" you ask?  There are a few ways.  In the previous post I mentioned how convert a memory stream to its base64 representation. 

A quick-and-dirty sample of how to do this from a file that exists on a server/HD would look like this (Update:  Per Petar's comment below, disposing of the FileStream object completely eluded me in my original version of the code sample below.  Updated to use using instead.)

protected void getBase64Image()
    using (FileStream imageStream = File.OpenRead("C:\\temp\\testImage.png"))
    byte[] data = new byte[imageStream.Length];
    imageStream.Read(data, 0, data.Length);
    string binaryRepresenatation = string.Concat("data:image/png;base64,", Convert.ToBase64String(data.ToArray()));
    //htmlImgTag looks like this: <img runat="server" id="htmlImgTag" />
    htmlImgTag.Src = binaryRepresenatation;

Additionally, you can do do one-off conversions of images from your HD or a URL using Hixie's Data URI Kitchen:

Lastly, Nicholas Zakas created the Java based CSSEmbed tool that will do this conversion for you from your CSS files on-the-fly.  I haven't tried it, but have heard good things:

As always, there are some things to watch out for using this technique. 

Firstly, data URI are not supported in all browsers...the wiki on Data URIs has some good info:

Second, as described by Rob Flaherty, there are some gotchas to watch out for.  The long and short of it is if you have a data URI that results in an image larger than 32k, it could negate this performance boost to some extent.  It's best to check out Rob's post on this for more detailed information:


Technorati Tags: ,

Sources: :)

Posted on Tuesday, December 1, 2009 4:04 PM | Back to top

Copyright © Sanjay Uttam | Powered by: