Last active
June 16, 2024 18:48
-
-
Save 1isten/0ec8c0bc78171c38a3d8b3cf48430a41 to your computer and use it in GitHub Desktop.
js compress image (base64) using canvas api
This file contains 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
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)); | |
} | |
}); |
Author
1isten
commented
Dec 17, 2020
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment