/** * 图片压缩,默认同比例压缩 * @param {Object} path * pc端传入的路径可以为相对路径,但是在移动端上必须传入的路径是照相图片储存的绝对路径 * @param {Object} obj * obj 对象有 width, height, quality(0-1) * @param {Object} callback * 回调函数有一个参数,base64的字符串数据 */ function dealImage(path, obj, callback) { var img = new Image(); img.src = path; img.onload = function() { var that = this; var ext = path.substring(path.lastIndexOf(".") + 1).toLowerCase(); // 默认按比例压缩 var w = that.width, h = that.height, MAX_WIDTH = w > 2500 ? w / 2 : 2500, MAX_HEIGHT = h > 2500 ? h / 2 : 2500; if (w > h) { if (w > MAX_WIDTH) { h *= MAX_WIDTH / w; w = MAX_WIDTH; } } else { if (h > MAX_HEIGHT) { w *= MAX_HEIGHT / h; h = MAX_HEIGHT; } } var quality = obj.quality; // 默认图片质量为0.7,可以为image/jpeg或image/webp类型的图片设置图片质量,取值0-1,超出则以默认值0.92替代 //生成canvas var canvas = document.createElement('canvas'); var ctx = canvas.getContext('2d'); canvas.width = w; canvas.height = h; ctx.drawImage(that, 0, 0, w, h); // 图像质量 if (obj.quality && obj.quality( = 1 && obj.quality > 0) { quality = obj.quality; } // quality值越小,所绘制出的图像越模糊 var base64 = canvas.toDataURL('image/jpeg', quality); callback(base64); } }
通过plus.zip.compressImage进行压缩处理。
通过plus.io.resolveLocalFileSystemURL生成文件对象。
通过plus.io.FileReader读取文件,生成base64字符串。
/** * 图片压缩,默认同比例压缩 * @param {Object} path * pc端传入的路径可以为相对路径,但是在移动端上必须传入的路径是照相图片储存的绝对路径 * @param {Object} obj * obj 对象有 width, height, quality(0-1) * @param {Object} callback * 回调函数有一个参数,base64的字符串数据 */ function dealImage(path, obj, callback) { var img = new Image(); img.src = path; img.onload = function() { var that = this; var ext = path.substring(path.lastIndexOf(".") + 1).toLowerCase(); // 默认按比例压缩 var w = that.width, h = that.height, MAX_WIDTH = w > 2500 ? w / 2 : 2500, MAX_HEIGHT = h > 2500 ? h / 2 : 2500; if (w > h) { if (w > MAX_WIDTH) { h *= MAX_WIDTH / w; w = MAX_WIDTH; } } else { if (h > MAX_HEIGHT) { w *= MAX_HEIGHT / h; h = MAX_HEIGHT; } } if (mui.os.ios) { plus.zip.compressImage({ src: path, dst: "_doc/cm.jpg", quality: 20, overwrite: true, width: '50%', clip: { top: "25%", left: "25%", width: "50%", height: "50%" } }, function(i) { plus.io.resolveLocalFileSystemURL(i.target, function(entry) { entry.file(function(file) { var reader = new plus.io.FileReader(); reader.onloadend = function(e) { let speech = e.target.result; //base64图片 callback(speech); }; reader.readAsDataURL(file); }, function(e) { mui.toast("读写出现异常: " + e.message); }) }) }, function(e) { console.error(JSON.stringify(e)) }); } else { var quality = obj.quality; // 默认图片质量为0.7,可以为image/jpeg或image/webp类型的图片设置图片质量,取值0-1,超出则以默认值0.92替代 //生成canvas var canvas = document.createElement('canvas'); var ctx = canvas.getContext('2d'); canvas.width = w; canvas.height = h; ctx.drawImage(that, 0, 0, w, h); // 图像质量 if (obj.quality && obj.quality( = 1 && obj.quality > 0) { quality = obj.quality; } // quality值越小,所绘制出的图像越模糊 var base64 = canvas.toDataURL('image/jpeg', quality); callback(base64); } } }