Skip to content

Instantly share code, notes, and snippets.

@semlinker
Created August 28, 2022 13:36
Show Gist options
  • Save semlinker/1b28f1ea2393f69308eddcc43065d113 to your computer and use it in GitHub Desktop.
Save semlinker/1b28f1ea2393f69308eddcc43065d113 to your computer and use it in GitHub Desktop.
image compression
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