Skip to content

Instantly share code, notes, and snippets.

@Tom910
Created January 6, 2023 12:03
Show Gist options
  • Save Tom910/2b20f870555cf1e8193c4ab370426af5 to your computer and use it in GitHub Desktop.
Save Tom910/2b20f870555cf1e8193c4ab370426af5 to your computer and use it in GitHub Desktop.
Compress An Image Before Upload With JavaScript
// https://pqina.nl/blog/compress-image-before-upload?ck_subscriber_id=887774617
<input type="file" multiple class="my-image-field" />
<script>
const compressImage = async (file, { quality = 1, type = file.type }) => {
// Get as image data
const imageBitmap = await createImageBitmap(file);
// Draw to canvas
const canvas = document.createElement('canvas');
canvas.width = imageBitmap.width;
canvas.height = imageBitmap.height;
const ctx = canvas.getContext('2d');
ctx.drawImage(imageBitmap, 0, 0);
// Turn into Blob
const blob = await new Promise((resolve) =>
canvas.toBlob(resolve, type, quality)
);
// Turn Blob into File
return new File([blob], file.name, {
type: blob.type,
});
};
// Get the selected file from the file input
const input = document.querySelector('.my-image-field');
input.addEventListener('change', async (e) => {
// Get the files
const { files } = e.target;
// No files selected
if (!files.length) return;
// We'll store the files in this data transfer object
const dataTransfer = new DataTransfer();
// For every file in the files list
for (const file of files) {
// We don't have to compress files that aren't images
if (!file.type.startsWith('image')) {
// Ignore this file, but do add it to our result
dataTransfer.items.add(file);
continue;
}
// We compress the file by 50%
const compressedFile = await compressImage(file, {
quality: 0.5,
type: 'image/jpeg',
});
// Save back the compressed file instead of the original file
dataTransfer.items.add(compressedFile);
}
// Set value of the file input to our new files list
e.target.files = dataTransfer.files;
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment