Recently, I have encountered a problem on the mobile side is:
Mobile phone photos, pictures too large if uploaded to the server must be wasted bandwidth, the most important is the traffic AH
Don't panic, the good things come, it must be someone to study the compression of the picture:
I combine the experience of predecessors, combined with their own actual combat, summed up a method for everyone to reference.
/** * image compression, default proportional compression * @param {Object} path * PC-side incoming path can be a relative path, However, the path that must be passed on the mobile side is the absolute path stored in the photo image * @param {object} obj * obj object has width, height, quality (0-1) * @param {Object} callback * callback function has a parameter, base64 string data*/function dealimage (path, obj, callback) {varIMG =NewImage (); IMG.SRC=path; Img.onload=function () {varthat = This; //default scaled compression varW =that.width, H=That.height, scale= w/h; W= Obj.width | |W; H= Obj.height | | (w/Scale ); varQuality =0.7;//default picture quality is 0.7//Build Canvas varCanvas = document.createelement ('Canvas'); varCTX = Canvas.getcontext ('2d'); //To Create an attribute node varANW = Document.createattribute ("width"); Anw.nodevalue=W; varAnh = Document.createattribute ("Height"); Anh.nodevalue=h; Canvas.setattributenode (ANW); Canvas.setattributenode (Anh); Ctx.drawimage (That,0,0, W, h); //Image quality if(Obj.quality && obj.quality <=1&& obj.quality >0) {Quality=obj.quality; } //The smaller the quality value, the more blurry the image is drawn. varBase64 = Canvas.todataurl ('Image/jpeg', quality); //callback function returns the value of Base64Callback (base64); } }
Of course the return is a string of base64;
If you can try to test the compressed picture size:
//calling a function to process a picture
dealimage ("path", { //Note: On the PC side can use absolute path or relative path, the mobile end is best with absolute path (because take photo after the picture path, I did not try to succeed (if someone tried to share experience))Width: $}, Function (Base){//directly to the Base64 string, put in an image tag, you can see the test after the compression of the style mapdocument.getElementById ("Transform"). src =Base; Console.log ("after compression:"+Base. Length/1024x768+" "+Base); })
Comprehensive: The main idea is to obtain pictures, using H5 canvas technology to image data into a base64 string, and finally uploaded to the background, the background will base64 string data for image storage.
Image compression (both PC-and mobile-compatible)