Skip to content

Instantly share code, notes, and snippets.

@patrickhulce
Created April 19, 2021 20:01
Show Gist options
  • Save patrickhulce/9b567031e760c8640f1be5a3acf79f4e to your computer and use it in GitHub Desktop.
Save patrickhulce/9b567031e760c8640f1be5a3acf79f4e to your computer and use it in GitHub Desktop.
Resize Image
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