1

I am using canvas.toDataURL() and getting the image in base64 format. But before uploading it to the server can I reduce the image's memory size say to 10KB? How can I do this using JavaScript or jquery?Code I am using is:

var context = canvas.getContext("2d");
context.drawImage(imageObj, c.x, c.y, c.w, c.h, 0, 0, canvas.width, canvas.height);
var vData = canvas.toDataURL();
user
  • 348
  • 5
  • 19

1 Answers1

3

If you want to compress the string you could attempt one of the compression algorithms mentioned here, but the DataURL is already fairly compressed, so this shouldn't make much of a difference.

Another option is to use the second parameter of the toDataURL specifying the quality of the JPG which can often be safely decreased without a visible effect on the image quality.

If the requested type is image/jpeg or image/webp, then the second argument, if it is between 0.0 and 1.0, is treated as indicating image quality; if the second argument is anything else, the default value for image quality is used. Other arguments are ignored.

Community
  • 1
  • 1
David Mulder
  • 26,123
  • 9
  • 51
  • 114
  • Yes I have read about "quality" factor of the image and is this reduces image's size say to 10KB? – user Mar 07 '13 at 09:20
  • @Ashwini: there is no 1:1 relation between quality and image size. It's rather exponential (as is the resulting quality). – Aaron Digulla Mar 07 '13 at 09:25
  • @Aaron Digulla: If I reduce the quality factor, image would not look that good right? otherwise, any other way for reducing the base64 image's size? – user Mar 07 '13 at 09:33
  • It's pointless to refer to 10KB if you don't describe the original image. And as far as the quality factor goes, the best and only way to know how big the effect is by reducing it. With certain kind of graphics I reduced it to about 30% and it was still fine, whilst with others I tend to export at around 90%. – David Mulder Mar 07 '13 at 10:51
  • @David Mulder: Ok thank you..I will use the "quality" parameter and reduce image's size. – user Mar 07 '13 at 11:09
  • 2
    @Ashwini: What you can do is to check the length of the result of `getDataUrl()` and reduce the quality until it's < 10KB. Use a binary search, that should be fast/accurate enough. – Aaron Digulla Mar 07 '13 at 12:38
  • @Aaron Digulla: How can I get the image's size pro-grammatically by the way? – user Mar 08 '13 at 05:06