Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a png to a base64 string using javascript?

I've tried several different options, so many I've lost track of them all. I'm making an AJAX request and the response is of Content-Type: image/png, and the contents are the actual image.

I would absolutely love to display the image, but nothing seems to work the way I want:

// imgdata contains a string that looks like this: "�PNG..."
var img = document.createElement('img');

// no good
img.src = 'data:image/png;base64,' + btoa(unescape(encodeURIComponent(data)));

// also no good
img.src = 'data:image/png;base64,' + btoa(encodeURIComponent(data));

// also no good
img.src = 'data:image/png;base64,' + btoa($.map(d, function(x){ return x.charCodeAt(0); }))

I've tried a few other things, but still no dice.

Is there any simple (or even complciated) way to do this in Javascript?

like image 766
Wayne Werner Avatar asked Apr 07 '26 00:04

Wayne Werner


1 Answers

This isn't done with base64 but with blob, but you'll get exactly the same result:

var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function(){
        if (this.readyState == 4 && this.status == 200){
            var img = document.getElementById('image');
            var url = window.URL || window.webkitURL;
            img.src = url.createObjectURL(this.response);
        }
    }
    // Relative path because : 
    // No 'Access-Control-Allow-Origin' header is present...
    xhr.open('GET', '/img/logo.png');
    xhr.responseType = 'blob';
    xhr.send();

Demo here : http://jsfiddle.net/sparkup/sp4cukee/

like image 97
Sparkup Avatar answered Apr 09 '26 14:04

Sparkup



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!