Last active
February 12, 2019 16:07
-
-
Save chaman-1/a64fcd49c9e1c0b6a41074fdecf0e5d0 to your computer and use it in GitHub Desktop.
Compress, resize images in JavaScript
This file contains hidden or 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