javascript - Why canvas enlarge image size? -


i want compress image user upload on front side.

source image 651kb(mac os), , after change size form (1920 * 1080) (1000 * 562), size of picture becomes 1.2mb(browser), 1.4mb(mac os), 1.29mb(windows 7). whatever, increase 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)     }   }) } 

the method toblob() no mime-type argument image type produce png file default lossless format , therefore typically larger source image of type jpeg.

change line:

canvas.toblob(function (b) {   console.log(readablesize(b.size)) }) 

to take image mime argument making use jpeg quality setting:

canvas.toblob(function(b) {   console.log(readablesize(b.size)) }, "image/jpeg", 0.7); 

experiment quality argument ([0.0, 1.0]) suit needs.


Comments

Popular posts from this blog

python Tkinter Capturing keyboard events save as one single string -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

javascript - Z-index in d3.js -