Created
November 13, 2021 14:40
-
-
Save marten-cz/880ccb449570fdf0c183073126f6986a to your computer and use it in GitHub Desktop.
Resize Image in JS
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 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