// Always redraw to JPEG: native compressImage changes quality, not dimensions. var MAX_SIDE = 1280; function compressToBase64(src, page) { return new Promise(function (resolve, reject) { my.getImageInfo({ src: src, success: function (info) { if (page.alive === false) { reject({ canceled: true }); return; } if (!(info.width > 0 && info.height > 0)) { reject(new Error('无法读取照片尺寸,请重新选择')); return; } var scale = Math.min(1, MAX_SIDE / Math.max(info.width, info.height)); var w = Math.max(1, Math.round(info.width * scale)), h = Math.max(1, Math.round(info.height * scale)); page.setData({ compressWidth: w, compressHeight: h }, function () { if (page.alive === false) { reject({ canceled: true }); return; } try { var ctx = my.createCanvasContext('compress-canvas'); ctx.clearRect(0, 0, w, h); ctx.drawImage(src, 0, 0, w, h); ctx.draw(false, function () { if (page.alive === false) { reject({ canceled: true }); return; } ctx.toTempFilePath({ x: 0, y: 0, width: w, height: h, destWidth: w, destHeight: h, fileType: 'jpg', quality: 0.88, success: function (result) { var file = result.apFilePath || result.tempFilePath; if (!file) { reject(new Error('照片处理失败,请重试')); return; } try { my.getFileSystemManager().readFile({ filePath: file, encoding: 'base64', success: function (r) { resolve('data:image/jpeg;base64,' + r.data); }, fail: reject }); } catch (e) { reject(new Error('当前淘宝版本不支持照片读取,请升级后重试')); } }, fail: reject }); }); } catch (e) { reject(new Error('照片处理不可用,请升级淘宝后重试')); } }); }, fail: reject }); }); } module.exports = { MAX_SIDE: MAX_SIDE, compressToBase64: compressToBase64 };