Skip to content

Instantly share code, notes, and snippets.

@chaman-k
Last active June 2, 2020 20:08
Show Gist options
  • Save chaman-k/de8566f1f05662fa35f6a56bd728e5b6 to your computer and use it in GitHub Desktop.
Save chaman-k/de8566f1f05662fa35f6a56bd728e5b6 to your computer and use it in GitHub Desktop.
Compress, resize images in javascript
/*
<!-- 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