'Getting PNG image as response from REST call in servicenow, The response is in junk character

I have situation here where I am getting PNG image as response from REST call in servicenow, The response is in junk character as shown below, I am writing server script which takes the response and convert in some string, which will be return to client UI action script to render as image back to UI page. I was not able to find any similar cases if someone has encountered similar situation please do share. any help would be appreciated

REST Response:

    IHDRU�  ��bKGD������� IDATx��{\T��� o"r�("r ���J(/���L��f�Syˬcio ��x��T�
    S�$=��JO�GE1 �xA@ T  �\��g���53kX��}? >ʞg�<���ڿ��� �/_V� � �Л���hj A A r������Ro�ݻwS�!� ��%���@�*� � c@�*� � #@�*� � #`�[B A a~DEE5�=44���T�"� �h���P���bԨQ�� �*UA A Z(++Crr2,--��� ++�C' T A A4��۷����nݺ�gϞ8�<z��UO�*� � �x��!� 
    kkk@HHH�z T A [email protected]�m���A A  �Du� � #A � � �  �&����ӧn��M� �  ���zPU^��|�)`�/���u�&vD A DS�:Q�U·����=���.X�Ď� �hj,,,0z�hXXXT* ���������{�p��o5����[�� � ���� ������AMM 233akk�Uo����W���\�{Uy9��^݄�� � �~��!++ ǎ ñcǐ��   �z� TM  ����(�9 o''���dL  k�9YYY��g�@ٱcLz�^X�r� �y��E��Y�� ��r�ͪ�kVx�f��5+��vJ��� � Ƙ1c0f�   < gΜѪ7�A�>TTTp��E�v�xa���7�杧 ��f�SV ���7�^�Y��U/׬���� ���666�t���\�P]Q����E/W��w�^��UOY1\/W�O�-.Z���M�]�Ӹx�k�Y�r�
    KN��Y)..��1����� �/_V@�޽�b@�|��'X�n]S� �h�T�*��R+IZ�@ g7������ c � "**�ޒ
    ������^��I?rb�@��EHE�¢��o��;O/r�ͪ�� ���o����T�vR� �jʸx�k�Y�r�
    KN�ڬ��� �*++�P(���HOO��$ �� R�9..Lz��Y|����;== 6���>O��S ߬z ߼�o<��<s+W�j}��L��ҫ�ӺءBU!��M����� �_aɉ�� ?{��<?%%
    ��y��T ��2��{ �鿴�4��� ] � %�0�*��  �\}l�yz��oV=e�p�\}�� = `�^�vR� ���;K;�{�k�Y�r�
    KN�ڬ�47S�N������͛��lll��� GG�::��? T=��T A�E�= �ߔ�I���% ���KN>s�� ?�~��iQyyyHLLDppp  ͩ2Q�g��"� �'�0��f�SV ��
....truncated since its too long


Solution 1:[1]

Your are passing the data as binary... old javascript can't handle binary data.

This is the correct/modern way to display ajax images.

but check compatibility ...

https://developer.mozilla.org/en-US/docs/Web/API/URL.revokeObjectURL

function showImg(e){
 var img=document.createElement('img');
 img.onload=function(e){
  document.body.appendChild(img);
  window.URL.revokeObjectURL(img.src);//Clear
 };
 img.src=window.URL.createObjectURL(this.response);
}

window.URL=window.URL||window.webkitURL;

var xhr=new XMLHttpRequest;
xhr.open('GET','/path/to/image.png',true);
xhr.responseType='blob';//Blob
xhr.onload=showImg;
xhr.send();

there is a more compatible way to d o that with

new Uint8Array

but i noticed some memory leaks.

if you want i can also post that code.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1