How to Base64 encode your images

A few weeks ago Google started including Instant Previews in their Google Instant SERPs. For this Google uses the same trick they’ve been using on YouTube results in the SERPs, presenting the images with Base64 encoding. The main purpose for Google is to reduce the number of HTTP request to their servers. If every SERP would require 10 additional images to be loaded it would most definitely impact the ‘perceptual speed’ at which the website is loaded. With Base64 encoding image data can be send inline and it wouldn’t require additional HTTP requests, just some extra milliseconds for sending this data.

You can easily implement this in your own website or application, just take a look at the PHP code below.

$img_src = "img/sample.jpg";
$imgbinary = fread(fopen($img_src, "r"), filesize($img_src));
$img_str = base64_encode($imgbinary);
echo '<img src="data:image/jpeg;base64,'.$img_str.'" alt="Alt text" />';

Uses this wisely and don’t go overboard, images presented through Base64 aren’t cached and using this for every image on your website would most definitely impact your site’s performance. Use it for on-the-fly created and non-reusable content only!

Update: Joost de Valk has released a very nifty tool that allows you to base64 encode images, check it out!

11 Replies to “How to Base64 encode your images”

  1. oh, and, kids, don’t forget that base64-coding your content makes it grow about 30%, which, depending on the original file size of the content, usually ends up being a whole lot more to handle for both you and your website visitors than the overhead of an additional http request!

    1. Like I said, it’s primarily intended for on-the-fly created content. Even Google only does this for images < 20kb. In this way gzipping the served page should keep the 'impact' to a minimum.

  2. You can always put this on the CSS and it would be cached. Then again it will take more space than just using the image (33% more) because of the encoding. Might be worth doing, though, if the website has lots of small images and the CSS is compressed (mod_deflate) by saving on HTTP requests’ time.

  3. Pingback:
  4. thx for this great feature.

    just a question is it work with others files format gif and png ?

    if we put image/gif or image/png ?


  5. I’ve actually “sort of” been doing this for my logo and some other images in my site’s CSS file, have to say that works quite well 🙂

Comments are closed.

%d bloggers like this: