Created
June 15, 2018 15:07
-
-
Save asm-jaime/bf5f8314da76b7c6b431e69ba48c6867 to your computer and use it in GitHub Desktop.
convert Image url to Base64 with use fetch
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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