Canvas compressed image

Source: Internet
Author: User
1. Canvas. todataurl: compressed image

The todataurl method of canvas can export the content to an image in base64 encoding format. base64 encoding is 1/3 larger than the source file. However, this method can specify the image quality to be exported, therefore, the front-end can compress uploaded images. Obtain the local image address through fileapi, create an IMG element, draw the image into the canvas, and then export (compress) it ). For example:

$ (': File '). on ('change', function () {var file = This. files [0]; var url = webkiturl. createobjecturl (File);/* generate image * -------------------- */var $ IMG = new image (); $ IMG. onload = function () {// generate the ratio var width = $ IMG. width, height = $ IMG. height, scale = width/height; width = parseint (800); Height = parseint (width/scale); // generate canvas var $ canvas =$ ('# canvas '); vaR CTX = $ canvas [0]. getcontext ('2d '); $ canvas. ATTR ({width: width, height: height}); CTX. drawimage ($ IMG, 0, 0, width, height); var base64 = $ canvas [0]. todataurl ('image/JPEG ', 0.5); // sent to the server $. post ('upload. PHP ', {formfile: base64.substr (22)}, function (data) {comment ('character php'character .html (data) ;});} $ IMG. src = URL ;});
2. Problems

However, this method has some problems:

1. When the image on iOS is too large, the image will be squashed.

2. The compression quality cannot be specified on Android.

3. The image is read in through fileapi, and the vertical picture is set horizontally.

Fortunately, there are solutions to these problems:

1. Use iOS-imagefile-megapixel to split the large image into two blocks and read it to the canvas and then combine it (you can also set the image rotation)

2. Use javascript_javas_encode

3. Use metadata (not tested)

Reference: http://my.oschina.net/hzplay/blog/160806

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.