Last active
June 2, 2020 20:08
-
-
Save chaman-k/de8566f1f05662fa35f6a56bd728e5b6 to your computer and use it in GitHub Desktop.
Compress, resize images in javascript
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
/* | |
<!-- HTML Part --> | |
<input id="file" type="file" accept="image/*"> | |
<script> | |
document.getElementById("file").addEventListener("change", function (event) { | |
compress(event); | |
}); | |
</script> | |
*/ | |
compress(e) { | |
const width = 500; | |
const height = 300; | |
const fileName = e.target.files[0].name; | |
const reader = new FileReader(); | |
reader.readAsDataURL(e.target.files[0]); | |
reader.onload = event => { | |
const img = new Image(); | |
img.src = event.target.result; | |
img.onload = () => { | |
const elem = document.createElement('canvas'); | |
elem.width = width; | |
elem.height = height; | |
const ctx = elem.getContext('2d'); | |
// img.width and img.height will contain the original dimensions | |
ctx.drawImage(img, 0, 0, width, height); | |
ctx.canvas.toBlob((blob) => { | |
const file = new File([blob], fileName, { | |
type: 'image/jpeg', | |
lastModified: Date.now() | |
}); | |
}, 'image/jpeg', 1); | |
}, | |
reader.onerror = error => console.log(error); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment