JS image compression (applicable to both pc and mobile) and js Image Compression
Recently, I encountered a problem on the mobile terminal: after taking a photo on the mobile phone, if the picture is too large, it will be a waste of bandwidth if it is uploaded to the server. The most important thing is the traffic, be sure someone will study image compression:
In combination with the experience of our predecessors and actual practices, you can summarize a method for your reference:
/*** Image compression. By default, the image is compressed in the same proportion. * @ param {Object} path * the pc-side input path can be a relative path, however, on the mobile terminal, the input path must be the absolute path for storing the photographic image * @ param {Object} obj *. The Object has width, height, and quality (0-1) * @ param {Object} callback * The callback function has a parameter, base64 string data */function dealImage (path, obj, callback) {var img = new Image (); img. src = path; img. onload = function () {var that = this; // by default, the var w = that is compressed proportionally. width, h = that. height, scale = w/h; w = obj. width | w; h = obj. height | (w/scale); var quality = 0.7; // The default image quality is 0.7 // generate canvas var canvas = document. createElement ('canvas '); var ctx = canvas. getContext ('2d '); // create an attribute node var anw = document. createAttribute ("width"); anw. nodeValue = w; var anh = 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 blurrier the image to be drawn. var base64 = canvas. toDataURL ('image/jpeg ', quality); // The callback function returns the base64 value callback (base64 );}}
Of course, a base64 string is returned;
If you can try to test the size of the compressed image:
// Call the function to process the image dealImage ("path", {// note: the absolute or relative path can be used on the pc end, it is best to use absolute path on the Mobile End (because the image path after taking photo is used, I have not tried it successfully (if someone has tried it successfully, share the experience) width: 200 }, function (base) {// directly put the obtained base64 string into an image tag and you will be able to see the compressed style chart document after the test. getElementById ("transform "). src = base; console. log ("compressed:" + base. length/1024 + "" + base );})
PS: The main idea is to get the image, use the H5 canvas technology to convert the image data into a base64 string, and then upload it to the background for image storage.
The above is all the content of this article. I hope this article will help you in your study or work. I also hope to provide more support to the customer's home!