const resizeMe = (img, maxW, maxH, nocheck) => {
const browser = {
versions: function () {
var u = navigator.userAgent;
return {
trident: u.indexOf('Trident') > -1,
presto: u.indexOf('Presto') > -1,
webKit: u.indexOf('AppleWebKit') > -1,
gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1,
mobile: !!u.match(/AppleWebKit.*Mobile.*/),
ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/),
android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1,
iPhone: u.indexOf('iPhone') > -1,
iPad: u.indexOf('iPad') > -1,
webApp: u.indexOf('Safari') == -1,
weixin: u.toLowerCase().match(/MicroMessenger/i) == 'micromessenger',
qq: u.match(/\sQQ/i) == " qq"
};
}()
};
var canvas = document.createElement('canvas');
var width = img.width;
var height = img.height;
var max_width = maxW || 640;
var max_height = maxH || 640;
var max_size = 5120;
if (width > max_width) {
height *= max_width / width;
height = Math.round(height);
width = max_width;
}
if (height > max_height) {
width *= max_height / height;
width = Math.round(width);
height = max_height;
}
if (browser.versions.ios || browser.versions.webApp) {
var mpImg = new MegaPixImage(img);
canvas.width = width;
canvas.height = height;
mpImg.render(canvas, {width: width, height: height});
} else {
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, width, height);
}
var res, quality = .7, resSize, ratio = 1;
res = canvas.toDataURL("image/jpeg", quality);
if (res.substr(0, "data:image/png".length) == "data:image/png" || res.substr(0, 6) == "data:,") {
var encoder = new JPEGEncoder();
res = encoder.encode(canvas.getContext("2d").getImageData(0, 0, width, height), quality * 100, true);
}
resSize = Math.ceil(res.length / 1024);
if (resSize > max_size && !nocheck) {
ratio = Math.ceil(Math.sqrt(max_size / resSize) * 100) / 100;
if (ratio >= .9) {
ratio -= .1;
}
res = resizeMe(img, max_width * ratio, max_height * ratio, true);
}
return res;
}