前端代码进行图像压缩

<html> <head> </head> <!--前端代码进行图像压缩--> <body> <input id="file" type="file"> </body>

<!--
    //基本思想 将图片尺寸等比压缩到最大高度,然后画到画布上,将画布转为图片
-->
<script>
    var maxHeight = 1024;
    var maxWidth = 1024;
    //获取到上传文件的元素
    var el = document.getElementById("file");
    el.addEventListener('change', function(event) {
        var file = event.target.files[0];
        var size = file.size;
        console.log('origin size:', size)
        minPicture(file, maxHeight, maxWidth)
        .then( (fileBlob) => {
            //获取到blob就可以做想做的事情了,比如转为URL
            console.log(fileBlob);
        })
    })

    function minPicture(file, maxHeight, maxWidth) {
        var canvas = document.createElement("canvas");
        var reader = new FileReader();
        var img = new Image();
        var ctx = canvas.getContext('2d');
        return new Promise((resolve, reject) => {
            img.addEventListener('error', reject);
            img.addEventListener('load', function () {
                var height = img.height;
                var width = img.width;
                //计算一个合适的压缩比例,
                //如果高度超过规定的,通过高度进行等比压缩
                //如果宽度超过规定的,通过宽度压缩
                //如果高度、宽度都超过,则使用需要压缩比例大的数字作为压缩比例
                let rate = 1;
                if (maxWidth && width > maxWidth) {
                    rate = width / maxWidth;
                }
                if (maxHeight && height > maxHeight) {
                    let rate2 = height / maxHeight;
                    if (rate2 > rate) {
                        rate = rate2;
                    }
                }
                //更新压缩后的高度宽度
                height = height / rate;
                width = width / rate;
                img.height = height;
                img.width = width;
                canvas.height = height;
                canvas.width = width;
                //清楚画布内容
                cxt.clearRect(0, 0, width, height);
                //绘制图像到画布
                cxt.drawImage(img, 0, 0, width, height);
                //图像转为Blob,也可以转为url
                canvas.toBlob(resolve);
            });

            reader.addEventListener('error', reject);
            reader.addEventListener('load', function () {
                img.src = reader.result;
            });
            reader.readAsDataURL(file);
        })
    }
</script>

</html>

猜你喜欢

转载自my.oschina.net/wanglihui/blog/1631261