Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safari img element won't render image retrieved from service (e.g., Dropbox) as ArrayBuffer using blob URL

Services such as Dropbox can download an image, return the file's data in various forms, including as an ArrayBuffer. In Webkit, it's possible to create a blob: URL that references the downloaded data and then set that as an img element's src attribute.

Example: http://jsfiddle.net/Jan_Miksovsky/yy7Zs/ retrieves an image's data as an ArrayBuffer, then creates a blob: URL and hands that to an img element. This example works in Chrome, but not Safari 6.0.2.

According to Can I Use (http://caniuse.com/#feat=bloburls) and other sources, Safari 6.x supports the creation of blob object URLs. And Safari does indeed support the use of createObjectURL via the prefixed global webkitURL. However, if the resulting blob URL is passed to an img element's src, the image is not rendered.

Is there some other way in Safari to render an image retrieved in this way?

like image 485
Jan Miksovsky Avatar asked Nov 04 '22 02:11

Jan Miksovsky


1 Answers

I just answered this question: HTML5 iPhone dynamic caching of images

where you can download an image from ajax and convert it to a base64 string. Then you can use this string to load an IMG element.

I have tested in safary 6.0.4 and it works. (I am not sure in 6.0.2).

Here is the code:

function _arrayBufferToBase64( buffer ) {
    var binary = '';
    var bytes = new Uint8Array( buffer );
    var len = bytes.byteLength;
    for (var i = 0; i < len; i++) {
        binary += String.fromCharCode( bytes[ i ] );
    }
    return window.btoa( binary );
}


var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://jsbin.com/images/favicon.png', true);
xhr.responseType = 'arraybuffer';

xhr.onload = function(e) {
        if (this.status == 200) {
          var string_with_bas64_image = _arrayBufferToBase64(this.response);
          document.getElementById("img").src = "data:image/png;base64," + string_with_bas64_image;
        }
};

xhr.send();

You can test it here:

http://jsbin.com/ivifiy/1/edit

like image 59
jbaylina Avatar answered Nov 08 '22 02:11

jbaylina