Skip to content

Instantly share code, notes, and snippets.

@andrIvash
Created November 27, 2024 07:56
Show Gist options
  • Save andrIvash/ecca704e359316ed98e200d74f1e0bf7 to your computer and use it in GitHub Desktop.
Save andrIvash/ecca704e359316ed98e200d74f1e0bf7 to your computer and use it in GitHub Desktop.
getBase64FromImageUrl
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