Follow me: @D_mitar

Most read posts recently



Feb 18th 2011 × Compressing jpeg images via base64 data and gzip deflating

Jpeg images are already fairly compressed. Applying gzip inflate/deflate to them does not gain much whereas gzipping files with a text content type (.css, .js, .html) usually gives pretty good results. This all led me to think, what happens if I take a decent sized jpeg image, convert it to a data:image base64 set and stick it in a dedicated css file. It will then be crunched by apache and much less data should be sent to the client browser.

So much for the theory. Here’s the actual test file.
http://fragged.org/dev/base64.html

- testing with image: http://fragged.org/dev/map-shot.jpg -133.6Kb
- dedicated CSS file: http://fragged.org/dev/base64.css -178.1Kb
- GZIP encoding server side enabled.

Resulting size sent to client (YSLOW components test): 59.3Kb! That’s a whopping saving of 74.3Kb – less data is being sent to the browser and most importantly, the jpeg quality remains the unchanged.

yslow components

Just a thought… I wish IE6 supported base64.


Feb 11th 2011 × Feature detect base64 image support, revisited

Recently I had cause to revisit my old routine that checks if a browser can work with base64-encoded images. This is a test that modernizr does not offer so the only way to do so is to Feature-detect. To the rescue: an empty 1x1px gif image gets encoded and is then set as the src of a new Image element, then tested. If base64 is supported, the resulting image object will have width and height of exactly 1px.

Here’s the code, extending the MooTools Browser.Features object, NEARLY synchronous (best check with a 50ms delay though or loop while Browser.Featrues.base64 === null):

(function() {
    Browser.Features.base64 = null;
    var callback = function() {
        Browser.Features.base64 = this.width == 1 && this.height == 1;
        // alert(Browser.Features.base64); // true || false
    };

    var img = new Image(), img = document.id(img) || new Element("img");
    img.onload = img.onerror = img.onabort = callback;
    // 1x1 px gif to test with
    img.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";

})();

And to see it in action:
http://www.jsfiddle.net/dimitar/5JT45/13/show/ or editable jsfiddle

Gist: https://gist.github.com/821370

An encoding tool that can help you convert your images: binary to base64 translator.

In reality, IE7 upwards supports it fine so all this “Feature Detect” can be skipped but it’s somewhat nicer that way.