Compress image in browser? Easy!
Anton Reshetov
Posted on February 12, 2019
First of all I want to thank people who are interested in the project MySigMail - UI Email Signature Generator.
In repo came an interesting PR where it was implemented a way to compress the image in the browser, without using the server.
I would like to share the code:
function compressImage (base64) {
const canvas = document.createElement('canvas')
const img = document.createElement('img')
return new Promise((resolve, reject) => {
img.onload = function () {
let width = img.width
let height = img.height
const maxHeight = 200
const maxWidth = 200
if (width > height) {
if (width > maxWidth) {
height = Math.round((height *= maxWidth / width))
width = maxWidth
}
} else {
if (height > maxHeight) {
width = Math.round((width *= maxHeight / height))
height = maxHeight
}
}
canvas.width = width
canvas.height = height
const ctx = canvas.getContext('2d')
ctx.drawImage(img, 0, 0, width, height)
resolve(canvas.toDataURL('image/jpeg', 0.7))
}
img.onerror = function (err) {
reject(err)
}
img.src = base64
})
}
Thanks @mykeels
MySigMail always happy to have contributors :)
Now I am working on version 2 in which there will be a WYSIWYG email editor.
Therefore, I would be happy if there are willing to help me in the development of templates for signatures in version 1.
💖 💪 🙅 🚩
Anton Reshetov
Posted on February 12, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.