JS Image Compression (pc and Mobile)
- 2021-07-10 18:29:55
- OfStack
Recently, I encountered a problem in doing mobile: After taking pictures with my mobile phone, if the picture is too large and uploaded to the server, it must waste bandwidth. The most important thing is traffic. Don't panic. When a good thing comes, someone must study the compression of pictures:
I combined my predecessors' experience and my own actual combat, and summed up a method for your reference:
/**
* Picture compression, default to the same scale compression
* @param {Object} path
* pc The path incoming from the mobile terminal can be relative, but the path that must be incoming from the mobile terminal is the absolute path of photographic picture storage
* @param {Object} obj
* obj Object Have width , height , quality(0-1)
* @param {Object} callback
* Callback functions have 1 Parameters, base64 String data of
*/
function dealImage(path, obj, callback){
var img = new Image();
img.src = path;
img.onload = function(){
var that = this;
// Default scaled compression
var w = that.width,
h = that.height,
scale = w / h;
w = obj.width || w;
h = obj.height || (w / scale);
var quality = 0.7; // The default picture 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;
}
// quality The smaller the value, the more blurred the image is drawn
var base64 = canvas.toDataURL('image/jpeg', quality );
// Callback function returns base64 Value of
callback(base64);
}
}
Of course, one string of one base64 is returned;
If you can try to test the compressed picture size under 1:
// Calling functions to process pictures
dealImage(" Path ", {
// Note: In pc End can use absolute path or relative path, and mobile end should use absolute path (because using take photo After the picture path, I didn't try it successfully (if someone tries it successfully, they can share it 1 Experience below))
width : 200
}, function(base){
// Directly will get the base64 The string of, put in the string of 1 A image Tag, you can see the compressed style diagram after testing
document.getElementById("transform").src = base;
console.log(" After compression: " + base.length / 1024 + " " + base);
})
PS: The main idea is to get the picture, use H5 canvas technology to convert the picture data into base64 string, and finally send it to the background, and the background will store the base64 string data graphically.