Created
April 19, 2021 20:01
-
-
Save patrickhulce/9b567031e760c8640f1be5a3acf79f4e to your computer and use it in GitHub Desktop.
Resize Image
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
function resize(imageDataUrl) { | |
return new Promise((resolve, reject) => { | |
const img = new Image() | |
img.addEventListener('error', reject) | |
img.addEventListener('load', () => { | |
try { | |
canvas.width = img.width | |
canvas.height = img.height | |
context.drawImage(img, 0, 0) | |
const imageData = context!.getImageData(0, 0, img.width, img.height) | |
canvas.toBlob(resolve, 'image/jpeg', 0.9) | |
} catch (err) { | |
reject(err) | |
} | |
}) | |
}) | |
img.src = imageDataUrl | |
} | |
document.querySelector('.my-file-input').addEventListener('change', event => { | |
const reader = new FileReader() | |
reader.addEventListener('load', async e => { | |
const resizedBlob = await resize(e.target.result) | |
// DO WHATEVER YOU NEED TO DO WITH THE BLOG TO SUBMIT THE FORM | |
}) | |
reader.readAsDataURL(event.files[0]); | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment