0

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.

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
Jake Carr
  • 71
  • 7
  • That's not Base64 - that is just the binary data. You need to convert it to Base64 on the server before returning. Are you sure you want to store large amounts of data in local storage? – Lee Willis Dec 16 '15 at 10:48
  • @LeeWillis Thank you for clearing that up for me. Yeah, unfortunately I have to because I'm making an app that downloads content that needs to work offline. – Jake Carr Dec 16 '15 at 10:55

2 Answers2

3

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).

Kaiido
  • 123,334
  • 13
  • 219
  • 285
0

You should convert the image to base64 first.

Try this link

How to convert image into base64 string using javascript

Community
  • 1
  • 1
Tony Hsieh
  • 153
  • 1
  • 1
  • 10