Created
May 2, 2024 18:39
-
-
Save scull7/0a7957903a0518ec024daae33374209c to your computer and use it in GitHub Desktop.
Convert Image to DataURL (browser)
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
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