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