Super simple image compression method (native js)

data为图片的base64数据
quality  为压缩的质量 0 - 1
//图片压缩
function PictureCompression(data,quality) {
    
    
    return new Promise((resolve,reject) =>{
    
    
        let imga = document.createElement('img');
        imga.src = data;
        imga.style.width = '300px';
        imga.style.position = 'fixed';
        imga.style.top = '300px';
        imga.style.top = '-4000px';
        document.body.appendChild(imga);
        imga.onload = () => {
    
    
            let canvas = document.createElement('canvas');
            canvas.style.position = 'fixed';
            canvas.style.top = '-4000px';
            canvas.width = imga.width;
            canvas.height = imga.height;
            document.body.appendChild(canvas);
            var ctx = canvas.getContext('2d');
            ctx.drawImage(imga,0,0,canvas.width,canvas.height);
            var base64Img = canvas.toDataURL('image/jpeg',quality);
            document.body.removeChild(canvas);
            document.body.removeChild(imga);
            resolve(base64Img);
        }
    })
}

use


PictureCompression(XXXXXXXX,0.7).then(res =>{
    
    
	res  压缩后的base64
})

Guess you like

Origin blog.csdn.net/weixin_44655037/article/details/124242413