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 ?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With