Why canvas enlarge image size?

Viewed 396

I want compress image that user upload on front side.

source image is 651Kb(Mac OS), and after I change size form (1920 * 1080) to (1000 * 562), the size of picture becomes 1.2Mb(browser), 1.4Mb(Mac OS), 1.29Mb(Windows 7). whatever, it was increase the size of original image.

Why?

source image: http://7xoaqt.com1.z0.glb.clouddn.com/maikailun.jpg

code: https://codepen.io/maicss/pen/ayLgdo/

<input type="file" multiple accept="image/*">

<canvas></canvas>


const $ = document.querySelector.bind(document)
const input = $('input')
const canvas = $('canvas')
const ctx = canvas.getContext('2d')

const readableSize =  (size) => {
    return size / 1024 > 1024 ? (~~(10 * size / 1024 / 1024)) / 10 + 'MB' : ~~(size / 1024) + 'KB'
}

input.onchange = function (e) {
    const files = e.target.files;
    [].forEach.call(files, file => {
    const img = new Image()
    img.src = URL.createObjectURL(file)
    img.onload = function () {
        let radio = 1
        if (Math.min(this.height, this.width) > 1000) {
            radio = Math.max(this.height / 1000, this.width / 1000)
        }
        canvas.height = this.height / radio
        canvas.width = this.width / radio

        ctx.fillRect(0, 0, canvas.width, canvas.height);
        ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
        canvas.toBlob(function (b) {
            console.log(readableSize(b.size))
        })
        URL.revokeObjectURL(this.src)
    }
  })
}
1 Answers
Related