Created
March 9, 2019 22:49
-
-
Save colxi/c9ab898aa063e0943d4fae1840b982d8 to your computer and use it in GitHub Desktop.
getBase64Image() : Get the Base64 representation of an image from its url
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
// get an image blob from url using fetch | |
let getImageBlob = function(url){ | |
return new Promise( async resolve=>{ | |
let resposne = await fetch( url ); | |
let blob = resposne.blob(); | |
resolve( blob ); | |
}); | |
}; | |
// convert a blob to base64 | |
let blobToBase64 = function(blob) { | |
return new Promise( resolve=>{ | |
let reader = new FileReader(); | |
reader.onload = function() { | |
let dataUrl = reader.result; | |
resolve(dataUrl); | |
}; | |
reader.readAsDataURL(blob); | |
}); | |
} | |
// combine the previous two functions to return a base64 encode image from url | |
let getBase64Image = async function( url ){ | |
let blob = await getImageBlob( url ); | |
let base64 = await blobToBase64( blob ); | |
return base64; | |
} | |
// USAGE : | |
// getBase64Image( 'http://placekitten.com/g/200/300' ) | |
// .then( base64Image=> console.log( base64Image) ); | |
Run |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment