Recently, I encountered a problem in mobile phones: after taking pictures on mobile phones, if the pictures are too large, it will waste bandwidth if uploaded to the server. The most important thing is traffic. Don’t panic. When good things come, someone will definitely study the compression of the pictures:
I have summarized a method for your reference based on the experience of my predecessors and my own practical experience:
/** * Image compression, default compression * @param {Object} path * The path passed in by the PC side can be a relative path, but the path that must be passed in on the mobile side is the absolute path of the photographic image storage. * @param {Object} obj * obj object has width, height, quality(0-1) * @param {Object} callback * The callback function has a parameter, the string data of base64 */ function dealImage(path, obj, callback){ var img = new Image(); = path; = function(){ var that = this; // By default, scaled var w = , h = , scale = w / h; w = || w; h = || (w / scale); var quality = 0.7; // The default image quality is 0.7 // Generate canvas var canvas = ('canvas'); var ctx = ('2d'); // Create attribute node var anw = ("width"); = w; var anh = ("height"); = h; (anw); (anh); (that, 0, 0, w, h); // Image quality if( && <= 1 && > 0){ quality = ; } // The smaller the quality value, the more blurry the drawn image var base64 = ('image/jpeg', quality ); // The callback function returns the value of base64 callback(base64); } }
Of course, what is returned is a base64 string;
If you can try to test the compressed image size:
// Call function to process picturesdealImage("path", { // Note: You can use absolute paths or relative paths on the PC side, and it is best to use absolute paths on the mobile side (because I did not try successfully the picture path after taking photo (if someone succeeds in trying it, you can share your experience)) width : 200 }, function(base){ //Press the obtained base64 string directly into an image tag and you can see the compressed style diagram after testing. ("transform").src = base; ("After compression:" + / 1024 + " " + base); })
PS: The main idea is to obtain pictures, use H5 canvas technology to dataize the pictures into base64 strings, and finally pass them to the background, and the background image-based storage of base64 string data.
The above is all the content of this article. I hope that the content of this article will help you study or work. I also hope to support me more!