Skip to content

Instantly share code, notes, and snippets.

@giioohbernini
Created February 5, 2021 18:21
Show Gist options
  • Save giioohbernini/7f92596c8b8a11f0bd141dfa7ca89643 to your computer and use it in GitHub Desktop.
Save giioohbernini/7f92596c8b8a11f0bd141dfa7ca89643 to your computer and use it in GitHub Desktop.
Client-side image resizer with Javascript
const scaleCanvas = (canvas, scale) => {
const scaledCanvas = document.createElement('canvas')
scaledCanvas.width = canvas.width * scale
scaledCanvas.height = canvas.height * scale
scaledCanvas
.getContext('2d')
.drawImage(canvas, 0, 0, scaledCanvas.width, scaledCanvas.height)
return scaledCanvas
}
const readPhoto = photo => {
const canvas = document.createElement('canvas')
const img = document.createElement('img')
const handleFileReader = resolve => {
const reader = new FileReader()
reader.onload = e => resolve(e.target.result)
reader.readAsDataURL(photo)
}
const handleImageSrc = result => {
return new Promise(resolve => {
img.src = result
img.onload = resolve
})
}
const handleCanvas = () => {
canvas.width = img.width
canvas.height = img.height
canvas.getContext('2d').drawImage(img, 0, 0, canvas.width, canvas.height)
return canvas
}
return new Promise(handleFileReader)
.then(handleImageSrc)
.then(handleCanvas)
}
const resizeImage = ({ imageBlob, maxWidth: MAX_WIDTH, quality: QUALITY }) => {
return readPhoto(imageBlob).then(canvas => {
while (canvas.width >= 2 * MAX_WIDTH) {
canvas = scaleCanvas(canvas, 0.5)
}
if (canvas.width > MAX_WIDTH) {
canvas = scaleCanvas(canvas, MAX_WIDTH / canvas.width)
}
return new Promise(resolve => {
return canvas.toBlob(resolve, 'image/jpeg', QUALITY)
})
})
}
export default resizeImage
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment