1

I am using canvas for resize image upload by user.

Resolution of Image I upload is 4000x3000 and its size is 962 kb After resize image becomes 2000x1500 but its size increases to 2.1MB

Before resize enter image description here

After resize its become 2.1 MB

Resize code is:

fileReader.onload = function (event) {
var image = new Image();

image.onload=function(){
  document.getElementById("original-Img").src=image.src;
  var canvas=document.createElement("canvas");
  var context=canvas.getContext("2d");
  canvas.width=image.width/2;
  canvas.height=image.height/2;
  context.drawImage(image,0,0,image.width,image.height,0,0,canvas.width,canvas.height);

  document.getElementById("upload-Preview").src =  canvas.toDataURL();
  }
   image.src=event.target.result;
};

Why the file size of image increases?

freedomn-m
  • 27,664
  • 8
  • 35
  • 57
Haseeb Ahmad
  • 7,914
  • 12
  • 55
  • 133
  • How do you check the size? because `canvas.toDataURL()` returns a bas64 string and that is bigger than a binary representation of the image – Bernhard Apr 20 '18 at 07:40
  • With that much difference in size, it's probably because the original image was a JPEG, which uses a highly compressed format for encoding the data. **Edit** Yep, checking the link, it is indeed a JPEG. Use the [optional arguments](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toDataURL) to select JPEG output instead of PNG which is the default, but note that a base64 string is going to be 4/3 the actual size of the raw image data. – Patrick Roberts Apr 20 '18 at 07:42
  • @PatrickRoberts you mean canvas resize not works on jpeg? – Haseeb Ahmad Apr 20 '18 at 07:47
  • My statement was very clear. Your original image is a JPEG. Your output image is a PNG. [_**read the documentation**_](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toDataURL) and figure out how to output a JPEG instead. – Patrick Roberts Apr 20 '18 at 07:49

0 Answers0