Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

display PNG from http get request

i'm working with angular 4, I'm using an api that return an image with content-type : img/png

The http method :

return this.http.get('URL', this.options)
    .map((res: Response) => res.text());
// can be also : res.arrayBuffer() // res.blob()

The http get response (in text and in ARC ) is like that :

�PNG  IHDR��"͹�W�W��zؽ�|+q%�   ��Y������M缥{��U��H�ݏ)L�L�~�6/'6Q׌�}���:��l'���� �R�L�&�~Lw?�

I tried different methods to convert it and display it :

  • getting response as blob and convert it using :

     new Uint8Array(response)
    
  • Getting the image as arrayBuffer and then convert it using :

      arrayBufferToBase64(buffer) {
      let binary = '';
      let bytes = new Uint8Array(buffer);
      let len = bytes.byteLength;
      for (let i = 0; i < len; i++) {
        binary += String.fromCharCode(bytes[i]);
      }
      return window.btoa(binary);
     }
    

Both of them didnt worked for me and the image is not displaying.

My question so is , what is the real format of the response (blob, arraybuffer or text ) and how to display it ?

like image 959
belhadj haythem Avatar asked Oct 29 '17 14:10

belhadj haythem


1 Answers

You can achieve this using the fetch API.

Let's first return the response as a blob. And then you can use URL.createObjectURL() to create an file object.

fetch(URL)
  .then(res=>{return res.blob()})
  .then(blob=>{
    var img = URL.createObjectURL(blob);
    // Do whatever with the img
    document.getElementById('img').setAttribute('src', img);
  })

Demo

like image 183
Rusty Avatar answered Oct 04 '22 20:10

Rusty