Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A better test for base64 URI support (can I create a large base64-encoded image in JS?)

I'm using Modernizr to detect the features supported in the browser our users are running, so far so good. But I've come up against a theoretical problem when testing for base64 compatibility. The patch for this support is detailed here, and works- except for a weird case with IE8- it only allows base64 encoded images of up to 32KB.

I don't really want to embed a 32KB long base64 string inside my JS file, it'll add a crazy amount of bloat. So, could I create a 32KB- valid- image using JS? I'm thinking repeating some kind of pattern within a string until it reaches 32KB in length, that sort of thing. Or maybe taking an existing tiny string (like the one in the Modernizr patch) and adding junk data at the end that still results in a valid image.

I know next to nothing about base64 encoding, other than how to manipulate an existing image. Does anyone have any ideas?

like image 665
Alastair Avatar asked Jul 13 '11 14:07

Alastair


1 Answers

I think I have an answer. I tried all sorts of techniques (repeated text chunks in the PNG source that I could manually add, etc) until I found that adding line breaks appears to do the job:

    var b64test = new Image();
    b64test.onload = function() {
       alert("yay!")
    }

    b64test.onerror = function() {
       alert("boo")
    }

    /* A 1x1 GIF image */

    var base64str = "R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw=="
    while (base64str.length < 33000) {
        base64str = "\r\n" + base64str;
    }

    b64test.src= "data:image/gif;base64," + base64str;

Fails in IE8, works in IE9 and others. I'd love to hear any alternatives, though.

like image 130
Alastair Avatar answered Oct 20 '22 07:10

Alastair