compress-base64
Version:
compress base64
52 lines (51 loc) • 1.81 kB
JavaScript
/**
* compress-base64 v7.0.10 by sunsilent
* @license MIT
**/
const step = 0.001;
function compress(base64, options) {
const { type = 'image/jpeg', width, height, min = 0, max = 200, crossOrigin, quality } = options;
return new Promise((resolve, reject)=>{
let tq = quality || 0.8;
const img = new Image();
img.src = base64;
if ('string' == typeof crossOrigin) img.setAttribute('crossOrigin', crossOrigin);
let tw = width;
let th = height;
img.onload = ()=>{
if (isNaN(tw) && isNaN(th)) {
tw = img.width;
th = img.height;
} else {
if (!isNaN(tw) && isNaN(th)) th = tw * img.height / img.width;
if (isNaN(tw) && !isNaN(th)) tw = th * img.width / img.height;
}
img.width = tw;
img.height = th;
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
canvas.width = tw;
canvas.height = th;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
let base64 = canvas.toDataURL(type, tq);
while(base64.length / 1024 > max){
if (tq <= step) {
base64 = canvas.toDataURL(type, step);
break;
}
tq -= step;
base64 = canvas.toDataURL(type, tq);
}
while(base64.length / 1024 < min){
tq += step;
base64 = canvas.toDataURL(type, tq);
}
resolve(base64);
};
img.onerror = (error)=>{
reject(error);
};
});
}
export { compress as default };