美文网首页
图片预览 压缩

图片预览 压缩

作者: Mr丶T | 来源:发表于2019-11-15 16:44 被阅读0次

function changepic(fileDom){

    var reads= new FileReader();

    f=fileDom.files[0];

    reads.onload=function (e) {

        compress(e.target.result, 500, 0.5).then(function (val) {

        $('#uploadimg').attr("src",val);

        });

    };

    reads.readAsDataURL(f);

}


function compress(base64String, w, quality) {

    var getMimeType = function (urlData) {

        var arr = urlData.split(',');

        var mime = arr[0].match(/:(.*?);/)[1];

        return mime;

    };

    var newImage = new Image();

    var imgWidth, imgHeight;

    var promise = new Promise(resolve => newImage.onload = resolve);

    newImage.src = base64String;

    return promise.then(() => {

        imgWidth = newImage.width;

        imgHeight = newImage.height;

        var canvas = document.createElement("canvas");

        var ctx = canvas.getContext("2d");

        if (Math.max(imgWidth, imgHeight) > w) {

            if (imgWidth > imgHeight) {

                canvas.width = w;

                canvas.height = w * imgHeight / imgWidth;

            } else {

                canvas.height = w;

                canvas.width = w * imgWidth / imgHeight;

            }

        } else {

            canvas.width = imgWidth;

            canvas.height = imgHeight;

        }

        ctx.clearRect(0, 0, canvas.width, canvas.height);

        ctx.drawImage(newImage, 0, 0, canvas.width, canvas.height);

        var base64 = canvas.toDataURL(getMimeType(base64String), quality);

        return base64;

    });

}

相关文章

网友评论

      本文标题:图片预览 压缩

      本文链接:https://www.haomeiwen.com/subject/epysictx.html