Created
November 27, 2024 07:56
-
-
Save andrIvash/ecca704e359316ed98e200d74f1e0bf7 to your computer and use it in GitHub Desktop.
getBase64FromImageUrl
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
export function getBase64FromImageUrl(URL: string, width: number, height: number, setImageSize?: boolean):Promise<string> { | |
return new Promise((res, rej) => { | |
const img = new Image(); | |
img.src = URL; | |
img.onload = function() { | |
const canvas = document.createElement("canvas"); | |
canvas.width = width; | |
canvas.height = height; | |
const ctx = canvas.getContext("2d"); | |
setTimeout(() => { //additional timeout to support ios | |
if (setImageSize) { | |
ctx.drawImage(img, 0, 0, width, height); | |
} else { | |
ctx.drawImage(img, 0, 0); | |
} | |
const dataURL = canvas.toDataURL('image/webp', 0.8); | |
ctx.clearRect(0, 0, canvas.width, canvas.height); | |
res(dataURL); | |
}, 100); | |
}; | |
img.onerror = rej; | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment