Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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