img通过canvas方式转成base64,并压缩

请您移步我的新个人博客: https://moweiwei.com,谢谢!

img通过canvas转成base64,并压缩

function imgSrcToBase64(imgSrc, callBack) {
    function getBase64Image(img) {
        var canvas = document.createElement("canvas");
        var quality = 0.7;//压缩率
        var maxLen = 300;
        //生成比例
        var width = img.width,
            height = img.height;
        //计算缩放比例
        var rate = 1;
        if (width >= height) {
            if (width > maxLen) {
                rate = maxLen / width;
            }
        } else {
            if (height > maxLen) {
                rate = maxLen / height;
            }
        };
        img.width = width * rate;
        img.height = height * rate;
        canvas.width = img.width;
        canvas.height = img.height;
        var ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0, img.width, img.height);
        var ext = img.src.substring(img.src.lastIndexOf(".") + 1).toLowerCase();
        var dataURL = canvas.toDataURL("image/" + ext, quality);
        return dataURL;
    }
    var image = new Image();
    image.crossOrigin = "anonymous"; //防止跨域出错
    image.src = imgSrc;
    image.onload = function () {
        var base64 = getBase64Image(image);
        callBack(base64);
        return base64;
    }
}

你可能感兴趣的:(JavaScript)