Jake Carr Jake Carr - 1 year ago 58
AngularJS Question

How to turn a string of data into an image in Javascript?

I have a URL of an image that when I set the src of an img to, the img changes to the image on the URL.

I want to download this image as a string so I can store it in local storage.

So I get the image data using XMLHttpRequest and this returns data that looks like this:

a��.e��E�ʓu�|���ʘ�*GN�'��қ��u�� ��c��]�
�.N���RH!�O�m�Aa���Զ�0U @Pɬ��:�շ���
1��j2�Ŭo�@����>ɛP���:E�o}\O���r ��Ύ�
\��|x�+�0 ͤ,n�|������B����

I'm not sure what format this data is in. It could be Base64 based on some Google searching but not 100% sure. This is just what I get when I console.log it. The image data string has a length of 109095. The console freezes when I log this string, can't figure out why.

I then try to set the src of the img in javascript like this:

x.src = "data:image/jpg;base64," + imageData;

And it doesn't work.

Answer Source

If you want a dataURI version of your image, the best way is to set the XHR.responseType to "blob", and read the resulted response blob with a FileReader :

var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function(){
  var reader = new FileReader();
  reader.onload = function(){
     img.src = this.result;
     result.textContent = this.result;
xhr.open('GET', 'https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png');
<img id="img"/>
<p id="result"></p>

Of course, you'll have to make the call to the same origin, or to an open server (such as wikimedia one).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download