Created
June 20, 2020 05:21
-
-
Save thinhbuzz/2774cf7cce6c1b89132086f9ea9ca6c7 to your computer and use it in GitHub Desktop.
Optimize image before upload
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
export const IMAGE_OPTIMIZER_OPTIONS = { | |
MAX_WIDTH: 1920, | |
MAX_HEIGHT: 1080, | |
MAX_QUALITY: 0.8 | |
}; | |
export function optimizeImageFile(file, {MAX_WIDTH, MAX_HEIGHT, MAX_QUALITY} = IMAGE_OPTIMIZER_OPTIONS) { | |
return new Promise(resolve => { | |
const img = document.createElement('img'); | |
img.onload = () => { | |
const canvas = document.createElement('canvas'); | |
let ctx = canvas.getContext('2d'); | |
ctx.drawImage(img, 0, 0); | |
const imageWidth = img.width; | |
const imageHeight = img.height; | |
const scaleX = MAX_WIDTH / imageWidth; | |
const scaleY = MAX_HEIGHT / imageHeight; | |
const scale = Math.min(1, scaleX, scaleY); | |
let width = imageWidth * scale; | |
let height = imageHeight * scale; | |
canvas.width = width; | |
canvas.height = height; | |
ctx = canvas.getContext('2d'); | |
ctx.drawImage(img, 0, 0, width, height); | |
resolve(canvas.toDataURL(file.type, MAX_QUALITY)); | |
}; | |
const reader = new FileReader(); | |
reader.onload = event => { | |
img.src = event.target.result; | |
}; | |
reader.readAsDataURL(file); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment