Skip to content

Instantly share code, notes, and snippets.

@scull7
Created May 2, 2024 18:39
Show Gist options
  • Save scull7/0a7957903a0518ec024daae33374209c to your computer and use it in GitHub Desktop.
Save scull7/0a7957903a0518ec024daae33374209c to your computer and use it in GitHub Desktop.
Convert Image to DataURL (browser)
function imgElConvert($img) {
const canvas = document.createElement('canvas');
canvas.height = $img.naturalHeight;
canvas.width = $img.naturalWidth;
const ctx = canvas.getContext('2d');
ctx.drawImage($img, 0, 0, canvas.width, canvas.height);
return canvas.toDataURL();
}
function getImageDataUrl($el) {
return fetchImage($el).then(blobToBase64);
}
function fetchImage($el) {
return Promise.resolve($el.getAttribute('src'))
.then((url) => fetch(url))
.then((res) => res.blob());
}
function blobToBase64(blob) {
return new Promise((resolve) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result);
reader.readAsDataURL(blob);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment