Skip to content

Instantly share code, notes, and snippets.

@marten-cz
Created November 13, 2021 14:40
Show Gist options
  • Save marten-cz/880ccb449570fdf0c183073126f6986a to your computer and use it in GitHub Desktop.
Save marten-cz/880ccb449570fdf0c183073126f6986a to your computer and use it in GitHub Desktop.
Resize Image in JS
function resizeBase64Img(base64Str: string, maxWidth = 500, maxHeight = 500) {
return new Promise<string>((resolve) => {
const img = new Image();
img.src = base64Str;
img.onload = () => {
const canvas = document.createElement('canvas');
const MAX_WIDTH = maxWidth;
const MAX_HEIGHT = maxHeight;
let {width, height} = img;
if (width > height) {
if (width > MAX_WIDTH) {
height *= MAX_WIDTH / width;
width = MAX_WIDTH;
}
} else if (height > MAX_HEIGHT) {
width *= MAX_HEIGHT / height;
height = MAX_HEIGHT;
}
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d');
ctx?.drawImage(img, 0, 0, width, height);
resolve(canvas.toDataURL());
};
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment