-
-
Save waptik/4ed4862afc65ac3ac1085d3f42f1fd2e to your computer and use it in GitHub Desktop.
js compress image (base64) using canvas api
This file contains hidden or 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)); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment