Skip to content

Instantly share code, notes, and snippets.

@1isten
Last active June 16, 2024 18:48
Show Gist options
  • Save 1isten/0ec8c0bc78171c38a3d8b3cf48430a41 to your computer and use it in GitHub Desktop.
Save 1isten/0ec8c0bc78171c38a3d8b3cf48430a41 to your computer and use it in GitHub Desktop.
js compress image (base64) using canvas api
const toBase64 = (file) => new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = (e) => resolve(e.target.result);
reader.onerror = (err) => reject(err);
});
const compressBase64 = (src, quality = 0.5) => new Promise((resolve) => {
const img = new Image();
img.src = src;
img.onload = () => {
const canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
canvas.getContext('2d').drawImage(img, 0, 0, canvas.width, canvas.height);
resolve(canvas.toDataURL('image/jpeg', quality));
}
});
@1isten
Copy link
Author

1isten commented Dec 17, 2020

<input name="images" type="file" accept="image/*" multiple />

<script src="./compress-base64-imgs.js"></script>
<script>
  document.querySelector('input[name="images"]').addEventListener('change', async (e) => {
    for (file of e.target.files) {
      const origin = await toBase64(file);
      const compressed = await compressBase64(origin, 0.6);
      console.log({ origin, compressed });
    }
  });
</script>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment