Skip to content

Instantly share code, notes, and snippets.

@muhsalaa
Created April 24, 2020 05:36
Show Gist options
  • Save muhsalaa/9864da8dee69cc80395cf82da2426af1 to your computer and use it in GitHub Desktop.
Save muhsalaa/9864da8dee69cc80395cf82da2426af1 to your computer and use it in GitHub Desktop.
Simple promise based function to convert image url to base64 string
/**
* Convert a url of image to base64 string
* @param {string} imgUrl string of image url
*/
function convertBase64(imgUrl) {
return new Promise((resolve) => {
var img = new Image();
// onload fires when the image is fully loadded, and has width and height
img.onload = () => {
var canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
var dataURL = canvas.toDataURL('image/png');
return resolve({ dataURL, status: 'ok' });
};
// when image didn't exist
img.onerror = () => resolve({ dataURL: '', status: 'error' });
img.setAttribute('crossOrigin', 'anonymous'); //
img.src = imgUrl;
});
}
// usage
convertBase64('http://someurl.com/gambar/bagus.jpg')
.then((resp) => {
console.log(resp); // { dataURL: '', status: 'error' }
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment