Skip to content

Instantly share code, notes, and snippets.

@asm-jaime
Created June 15, 2018 15:07
Show Gist options
  • Save asm-jaime/bf5f8314da76b7c6b431e69ba48c6867 to your computer and use it in GitHub Desktop.
Save asm-jaime/bf5f8314da76b7c6b431e69ba48c6867 to your computer and use it in GitHub Desktop.
convert Image url to Base64 with use fetch
const fetch = require('node-fetch');
function btob64(buff) {
let binary = '';
const bytes = (new Array()).slice.call(new Uint8Array(buff));
for(let i = 0; i < bytes.length; ++i){
binary = binary + String.fromCharCode(bytes[i]);
}
return Buffer.from(binary.toString(), 'binary').toString('base64');
}
function get_type(url) {
const parts = url.split('.');
const last_one = parts[parts.length - 1];
if( last_one === 'png' ||
last_one === 'jpg' ||
last_one === 'jpeg' ||
last_one === 'gif' ||
last_one === 'bmp' ){
return last_one;
} else {
return '';
}
}
function urltob64(url) {
return new Promise((resolve, rejected) => {
const type = get_type(url);
if(type === '') rejected(false);
return fetch(url)
.then((res) => res.arrayBuffer())
.then((buf) => {
const b64flag = `data:image/${type};base64,`;
const imgStr = btob64(buf);
if(imgStr) {
resolve(`${b64flag}${imgStr}`);
} else {
rejected(false);
}
});
});
}
urltob64(
'https://user-images.githubusercontent.com'+
'/18028768/27010483-064cee7c-4ed8-11e7-8c5'+
'7-fac705fc0c50.png'
)
.then(console.log)
.catch(console.log);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment