img canvas方式でbase 64に変換し、圧縮する.

1350 ワード

私の新しい個人ブログに足を運んでください.https://moweiwei.comありがとうございます
canvasを通じてbase 64に変換し、圧縮する.
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;
    }
}