1

I have an API endpoint for image files and it always sends down the raw data. How do I show this image data on a website? Ideally I would like to use the img tag or css background-image property and not canvas.

Here is some code that could be used:

$.get({
  url: '/some-image',
  success: function(data) {
    // Load raw image data somewhere and show it on webpage.
  },
});

In my case I am actually using a library called axios but I have used a jquery example as I though it would be more well-known.

Just to be clear the data I receive looks like this:

����JFIF��� ( %!1!%)+...383-7(-.+ 
-------------+-------------+-+--+-----------+-----+���"����?!1AQa"q����2����R��Br�#b$4D�������%!1A2Q"Ca��?��]0`V�a����:T���E�R����$�jy$�6�GcP��Q��$�Fk,� ;D������\�e�l��(GE��[c,���w�P�&�J1rz.mM��]��!����\ �\̺I�:.�[&o=~z�7Y�'#T �_�%��u+����rg�i��p��^�����c���[E�ʔ����)E���b x�=U!M���3��6�k8��R��0&<?K�Kn���pd+'��Vt��|l�Z���i1�Pic*R79�8 b]A<�ݿ��@mw} kBjѲٸ�Tm��m�+ǖ���G�jv&��D:Ƽ$sD2zf
Rupert
  • 1,629
  • 11
  • 23

1 Answers1

1

Download it as a "blob" Convert the blob into a URL. Then specify that as the source for your image element.

The API for converting a Blob into a URL is createObjectUrl.

If your ajax library does not deal cleanly with blobs (for example, fetch gives you response.blob()), create one from raw bytes using new Blob([data], "image/jpeg") or equivalent.

  • What do you mean by _"Download it as a ""blob""_?`jQuery.ajax()` does not support binary data response by default, which OP is apparently unaware of. There is a gist which achieves binary data result https://gist.github.com/SaneMethod/7548768; see https://stackoverflow.com/questions/42106584/displaying-pdf-from-arraybuffer/42195304#42195304. – guest271314 Jul 12 '17 at 07:59
  • 1
    This actually helps me as I am using axios and they support blob it seems: https://github.com/mzabriskie/axios/blob/master/README.md#request-config – Rupert Jul 12 '17 at 08:25