Created
August 28, 2022 13:36
-
-
Save semlinker/1b28f1ea2393f69308eddcc43065d113 to your computer and use it in GitHub Desktop.
image compression
This file contains 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
const MAX_WIDTH = 800; | |
function compress(base64, quality, mimeType) { | |
let canvas = document.createElement("canvas"); | |
let img = document.createElement("img"); | |
img.crossOrigin = "anonymous"; | |
return new Promise((resolve, reject) => { | |
img.src = base64; | |
img.onload = () => { | |
let targetWidth, targetHeight; | |
if (img.width > MAX_WIDTH) { | |
targetWidth = MAX_WIDTH; | |
targetHeight = (img.height * MAX_WIDTH) / img.width; | |
} else { | |
targetWidth = img.width; | |
targetHeight = img.height; | |
} | |
canvas.width = targetWidth; | |
canvas.height = targetHeight; | |
let ctx = canvas.getContext("2d"); | |
ctx.clearRect(0, 0, targetWidth, targetHeight); | |
ctx.drawImage(img, 0, 0, canvas.width, canvas.height); | |
let imageData = canvas.toDataURL(mimeType, quality / 100); | |
resolve(imageData); | |
}; | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment