Jake Carr Jake Carr - 1 month ago 7
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:

�T��ǁ�Y�k����De,�GV��<A:V��TɕH'�:A�
a��.e��E�ʓu�|���ʘ�*GN�'��қ��u�� ��c��]�
�.N���RH!�O�m�Aa���Զ�0U @Pɬ��:�շ���
p�;2��Z���H����¯��P�un>�u�uj��+�쨯
��Z��֦DW>U����.U:V�{�&(My��kύO�S�������e��ԃ����w�
1��j2�Ŭo�@����>ɛP���:E�o}\O���r ��Ύ�
ob�P|b��/e�\@����k>��?mr<�ƭ�0~����f����\�i�^���ޟj��ٙI&=��B���N��(�N��C�kO�o3e�az�G
�|�����AO�A�6�2
�H�^�5��$�Ѭ
\��|x�+�0 ͤ,n�|������B����
w4ɞG�Q!�"�yb@�[A��\m)��߂�dA�h�.��6����q�αA0�bO��20*�LVX�<`Rv�W�6�f'hF���V���n`̌v�7�Ν��OI|���Ԙ�uoqk���n����g��a��ӗ>���Ԏt��


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

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;
    };
  reader.readAsDataURL(this.response);
  };
xhr.open('GET', 'https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png');
xhr.send();
<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).

Comments