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();
2
  • Could you show us what you have tried so far Commented Mar 7, 2013 at 8:57
  • @harsha:Edited my question. Commented Mar 7, 2013 at 9:16

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

7 Comments

Yes I have read about "quality" factor of the image and is this reduces image's size say to 10KB?
@Ashwini: there is no 1:1 relation between quality and image size. It's rather exponential (as is the resulting quality).
@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?
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%.
@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.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.