Display image from http response with image content type
Asked Answered
S

5

50

Let's say I have url and don't know what it will return. I perform ajax call to that url with javascript and get the content. So I test it's content-type and decide how to show response in my webpage. In case it is json or html or any other text, I append the formatted content as I need.

Now when the content type is image, I get the image's data in response, which is not base64 encoded. I need to show the image in a regular <img> tag of course. And here is where I get stuck.

Is there a way to show image from it's content data?

EDIT

Just to make it clear, hear is what I get in response:

"�PNG


IHDR��Nn�tEXtSoftwareAdobe ImageReadyq�e<fiTXtXML:com.adobe.xmp<?xpacket begin="" id="W5M0MpCehiHzreSzNTczkc9d"?> <x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="Adobe XMP Core 5.0-c060 61.134777, 2010/02/12-17:32:00        "> <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"> <rdf:Description rdf:about="" xmlns:xmpMM="http://ns.adobe.com/xap/1.0/mm/" xmlns:stRef="http://ns.adobe.com/xap/1.0/sType/ResourceRef#" xmlns:xmp="http://ns.adobe.com/xap/1.0/" xmpMM:OriginalDocumentID="xmp.did:8E935AD20E206811822AA1DC23D37A5E" xmpMM:DocumentID="xmp.did:606C15E3DC2311E2A81EB553B5E13CE0" xmpMM:InstanceID="xmp.iid:606C15E2DC2311E2A81EB553B5E13CE0" xmp:CreatorTool="Adobe Photoshop CS5 Macintosh"> <xmpMM:DerivedFrom stRef:instanceID="xmp.iid:0E49679B0D20681192B0DE3AF6794EF0" stRef:documentID="xmp.did:8E935AD20E206811822AA1DC23D37A5E"/> </rdf:Description> </rdf:RDF> </x:xmpmeta> <?xpacket end="r"?>�,��
3IDATx�읿R�JGI&m�����I����؅K((MC7�nH����%���ef����0���u�� i%����:�`K�{�ӷ������u�>���(����(����(����(����(����(����(����(����(����(��((��((��((��((��(���&؅�b1�ϟ׬V��t���j�T*��e��R��t�����c0�&��|}yy����ns�|Cc�l���7k�����ju:�Eٴ����")Ye�
W�U�Mu+"n�����3
����zzz*c��%����K�g4�&�T���z=_����G���@ū�(�Rġ�ng��^������@�F���2G_��],t�Fb:�����^������@٨  ��n�F#�`����|���<��_!��z���,��?�p}��U�����I}���
��h�6N��}||$hIY���p^IR?��
(k*��D�c���)�����s�*l�e�n-}��o��f:��Pְ[.��ʚKdP�be
�!9��,ʺh��!�r����|����>}��o����λW.��#�5�    
�5IY)Zx�'ʚ4�:88��P��̫����P֟Z��玍�czeM�51(()��4����0f�P�03���A�'���Y�5)he�xTʚ�����|��eQ�$�j�jF���~AY�~_������A��`����dOZ�=��f��%�{�}��Qi6�����+U,ʚ4N��E��(�J9^s�m�e� ǜ#bQ6�5�D,��G٘���e��?~��(?h3����*V
��
!��-V*���[ڜ�݉,���v�����2����    �Pְ8�PeQ��d0�g.eM�I�'�����}�
wˠlb�F��|�򤁳�����GٝY/..^^^dl���nU0����hv������������)m�������ec��z�yK�����ְn淳9������=�lT����4�q�'''�E)j��6q��b��:��T�U���F����%�܈M�� � �ْ���,��7�6�6�Ŭ���[ ��!;���7)x�9)�/�����S�*��������i��GAJ�~����jMh*�j�f�Y��UV�k8��G9r�v�^����O����\W 9}^V�q�`(�ʄb)+�9���IVj��k���������K�x�-֊��Z�Pe���h4�L�k�O8[󮢐*3ާ�;�`���b���qAFi�(U��\.�񶷞C�6_�ݮo(�Ri8���`P��k���P�դ&�|?Ǒ#���o=�V��dĵp�K���h�I  N�)%fY�I���Ǡ�LpWq��v"�ʦ��*��4^G4bsn��J7h�^*�z�����{���V�����(+}#����=�$�(+�z!H�><<���SJD�¯e� �Q6��xAxuu%rx�]v)�4�Y%�d�rK���z��x��Q�
:;�h�Iu�mZ�h��bC�������� F���g�וּ�B�AY��lje�Q]Ā\�V�y5ʆ��3�rߔ�x�_qN����� h�W6t�S�<??{񅝊{t��h8�l�ș:�  ��mE��Q�;Y*{��&�`0�x�������(V   f|��Yˆ���qfH�Z��z��i\�S3�LP6�/�� h��nП������>γ?NP6��2LaA/VP؜q!�2�Q6k�U��oWa�(��PK��+��V���(ky�0_�g��fIe����*;����t��A?W\)�qb��մ�lb���*�ex�˦y#�ir\�4��bWs�:9�
]�m�����K��=�瘲�����_�)��K���O�Ќ�R6�x�Ƽ"J���}Q�����)+�^�ymS�������kP��B6蔪�J}���/��٘�+�COo���f�0�1��5OY��{O�ێ����Ӫ1Q6��P�ޔ�䌬ɑc��:�����G�>gd���0e��{��Уț��L�73LY}�wsO��*��t��p�fe�*�\k�d�f*k5�o�Ԭa�jUx��F9�6G+e�e�R�n*���0��k��10��v6
�$`Vm�_w�v���pm�Y#0��ժ*�T6J-�j��*U��&���Γ���Z�X)kzU`�vyW">�9��|�)��]����F�;�e�E���*(�����ʂg����%�}���,�,��,�,�&���/���Q���0��0e#�0��T*�lZ-�~!�@R��V5l��j���>Em�)p}}mֹ���뫉m=�χá��ׁ���^�g\�e��.b��߿Y$�U% �v:�JX{�up^�8���]��@��_��Z��&��t<o{W��T*1�V���+��OOO��Wr��������L-��������~�kh�J�V��ڏR�]��b�r���1�Bu_�p����zq�W2X$�o�}"�HYYS.��o��S(RK�V+��}\a�7�;�)_���A�d��1#Y$vl�{��ͭ��!���i����T�e�X�
(��((��((��((��((��((��((��((��((��((��(����(����(����(����(��`/�0a�����IEND�B`�"
Schenk answered 26/12, 2013 at 11:34 Comment(1)
check this : #20036115Waine
U
40
var rawResponse = "�PNG...."; // truncated for example

// convert to Base64
var b64Response = btoa(rawResponse);

// create an image
var outputImg = document.createElement('img');
outputImg.src = 'data:image/png;base64,'+b64Response;

// append it to your page
document.body.appendChild(outputImg);
Unseen answered 26/12, 2013 at 21:54 Comment(6)
This should definitely be the canonical answer. Also, I think it'd be worth mentioning that btoa will work in this case, but needs help from unescape and encodeURIComponent for UTF-8.Aretha
Liked this approach. But in my case btoa throws this error: Uncaught InvalidCharacterError: 'btoa' failed: The string to be encoded contains characters outside of the Latin1 range. Even when I do unescape(encodeURIComponent(rawResponse)). By the way, unescape seems to be deprecated.Schenk
i am using filepath to upload an image while reciving i am getting similar to the above raw data but iam not able to convert to base64 btoa is giving some other result any idea why btoa is not providing base64Action
Is this something different for jpegs? i have the same thing with a jpeg however this method doesn't seem to work. After converting it all i am left with that funny icon on the frontend that displays when no image is there; <img src="data:image/jpg;base64,77+977+977+977+9ABBKRklGAAEBAQBIAEgAAO+/ve+/vRDvv71FeGlmAABNTQAqAAAACAAFARIAAwAAAAEAAQAAATEAAgAAAC4AAAhWATIAAgAAABQAAAjvv73vv71pAAQAAAABAAAI77+977+9HAAHAA....................vv73vv71uM++/vWnvv70R77+9dU/vv71c77+9BADvv70Zbe+/vQTvv71UdO+/ve+/vUXvv73vv71577+9B2t+HWjvv73vv73vv73vv73vv73vv70=">Letsou
@waqask87 did you find a solution for content-type jpeg ??Bo
Getting error - DOMException [InvalidCharacterError]: Invalid character at new DOMException (node:internal/per_context/domexception:53:5) at _node_internal (node:internal/util:695:10) at btoa (node:buffer:1268:13) at D:\empmgt\routes\generate-id-route.js:201:32 at process.processTicksAndRejections (node:internal/process/task_queues:95:5)Schweitzer
S
22

The accepted answer didn't worked for me. So here's my solution:

  1. I'm using fetch to download image, so I need to read response as blob:
let data;
fetch(url).then(response => {
  response.blob().then(blobResponse => {
    data = blobResponse;
  })
});
  1. Displaying blob as image:
const urlCreator = window.URL || window.webkitURL;
document.getElementById('myImage').src = urlCreator.createObjectURL(data);
Stav answered 9/5, 2017 at 13:56 Comment(2)
actually this is the answer that works and tutored by mozilla in here and hereHersh
This's the best answer to the questionNaresh
S
1

Solution

use the blob

Example

This example is to get the image from some repository of GitHub.

/**
 * @param {int} solutionNumber: I provide two solutions both can achieve.
 * @param {string} owner
 * @param {string} repo
 * @param {string} path
 * @param {string} branch: branch name or you can use SHA1
 * @param {string} token: Used while your repository is private. https://github.com/settings/tokens
 */
async function ShowGithubImg(solutionNumber, owner, repo, path, branch = "master", token = "") {
  const response = await fetch(`https://api.github.com/repos/${owner}/${repo}/contents/${path}?ref=${branch}`, {
    // method: "GET",
    headers: {
      accept: 'application/vnd.github.v3.raw',
      // authorization: `token ${token}`
    }
  })
  if (!response.ok) {
    const errMsg = await response.text()
    throw Error(`${response.statusText} (${response.status}) | ${errMsg} `)
  }

  const responseBlob = await response.blob()

  const img = document.createElement('img')

  switch (solutionNumber) {
    case 1:
      img.src = URL.createObjectURL(responseBlob)
      break
    case 2:
      let uriData = ""
      blob2bas64 = async (blob) => {
        const promise = new Promise((resolve, reject) => {
          const reader = new FileReader()
          reader.onload = function () { // use promise to wait until onload finished
            console.log(this.result) // you can see its media type is: application/vnd.github.v3.raw // https://docs.github.com/en/rest/overview/media-types
            uriData = this.result // <--- `this.result` contains a base64 data URI
            resolve()
          }
          reader.readAsDataURL(blob)
        })
        await promise
      }

      await blob2bas64(responseBlob)
      img.src = `${uriData}`
      break

  }
  document.querySelector(`body`).append(img)
}

for (const solutionNumber of [1, 2]) {
  ShowGithubImg(solutionNumber, "CarsonSlovoka", "excel", "app/urls/static/app.ico", "807dd79")
}

URI

@Lostsource's answer mentions Uniform Resource Identifier Since this question only asks about images, but some people have other formats (image/jpeg) In fact, the format of URI.scheme.data is

data:<mediatype>[;base64],<data>

👆 you can see it on Uniform Resource Identifier

You just need to know the mediatype (common mediatype list).

For example image/jpeg

data:image/jpeg;base64,<data>

Sourpuss answered 8/7, 2021 at 9:52 Comment(0)
B
0

I would convert the image to base64 using canvas toDataURL and then append it to the DOM like so:

var rawResponse = 'PNG'; // This is your response object
var encodedResponse = btoa(rawResponse);

var img = new Image();
var container = document.getElementById('newImg');

img.src = 'data:image/gif;base64,' + encodedResponse;

img.onload = function() {
container.appendChild( img );
};

More information on btoa

Barberabarberry answered 26/12, 2013 at 12:0 Comment(1)
I do not have the image url in frontend, just content. I am not sure how to create a canvas with that data.Schenk
E
0

we can get response and bind it form my HTML.

1) .ts file page : -

imageData : any ;

response => {
    var b64Response = btoa(response);
    this.imageData = 'data:image/png;base64,' + b64Response;
  }

2) .html file page:

      <img [src]="imageData" class="img-thumbnail">
Emancipation answered 3/12, 2019 at 9:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.