Fetching images with the Fetch Api

This is just a snippet that I want to share today with you because I think is something not a lot of javascript developers know.

It basically shows how to use the fetch api for retrieve an ArrayBuffer and later convert it to a btoa which you can easily display in you browser.

(The example is based on mashape meme generator api)

const url = 'https://ronreiter-meme-generator.p.mashape.com/meme?meme=Baby+Godfather&font_size=50&font=Impact&top=Thanks+m&bottom=Later';
const headers = new Headers({'X-Mashape-Key': 'API_KEY'});
const options = {
method: 'GET',
headers: headers,
mode: 'cors',
cache: 'default'
};
const request = new Request(url);

fetch(request, options).then((response) => {
response.arrayBuffer().then((buffer) => {
const base64Flag = 'data:image/jpeg;base64,';
const imageStr = arrayBufferToBase64(buffer);

document.querySelector('img').src = base64Flag + imageStr;
});
});

function arrayBufferToBase64(buffer) {
const binary = '';
const bytes = [].slice.call(new Uint8Array(buffer));

bytes.forEach((b) => binary += String.fromCharCode(b));

return window.btoa(binary);
};

The new kids of the neighbourhood

The forgotten ones

You can check it all together working in Merememe.com also the source code is available here.

Also don’t forget to use the fetch JavaScript and take a look to all the methods of the fetch Response.