Jquery 关于图片的压缩

var OneImgUpLoad = {
    OneImageType: 0,
    OneImageData: null,
    AddImg: function (id) {
        var MyFiles = $("#" + id).prop('files');
        var MyFile = MyFiles[0];
        //检验是否为图像文件  
        if (!(MyFile.type == 'image\/jpeg' || MyFile.type == 'image\/png')) {
            AlphaMS.JSToolkit.Dialog.MessageBox("请上传jpeg或png格式的图片文件!");
            return;
        }
        var imageUrl = OneImgUpLoad.getObjectURL(MyFile);
        OneImgUpLoad.convertImgToBase64(imageUrl, function (base64Img) {
          
            //图片数据
            var image_base64 = base64Img.split(",")[1];
            //图片数据
            OneImgUpLoad.OneImageType = MyFile.type == 'image\/jpeg' ? 1 : 2;
            OneImgUpLoad.OneImageData = image_base64;
            if (OneImgUpLoad.OneImageData != "") {
                $("#PhotoResultDiv").css("display", "block");
                $("#PhotoResult").attr("src", base64Img);
            }
            $("#" + id).html("");


        });
        event.preventDefault();

    },
    convertImgToBase64(url, callback, outputFormat) {
        var canvas = document.createElement('CANVAS');
        var ctx = canvas.getContext('2d');
        var img = new Image;
        img.crossOrigin = 'Anonymous';
        img.onload = function () {
            var width = img.width;
            var height = img.height;
            // 按比例压缩4倍
            var rate = (width < height ? width / height : height / width) / 4;
            canvas.width = width * rate;
            canvas.height = height * rate;
            ctx.drawImage(img, 0, 0, width, height, 0, 0, width * rate, height * rate);
            var dataURL = canvas.toDataURL(outputFormat || 'image/png');
            callback.call(this, dataURL);
            canvas = null;
        };
        img.src = url;
    },
    getObjectURL(file) {
        var url = null;
        if (window.createObjectURL != undefined) {  // basic
            url = window.createObjectURL(file);
        } else if (window.URL != undefined) {       // mozilla(firefox)
            url = window.URL.createObjectURL(file);
        } else if (window.webkitURL != undefined) { // web_kit or chrome
            url = window.webkitURL.createObjectURL(file);
        }
        return url;
    }

}
posted @ 2020-09-24 13:22  LowKeyC  阅读(856)  评论(0编辑  收藏  举报
有志者事竟成破釜沉舟百二秦关终属楚苦心人,天不负,卧薪尝胆,三千越甲可吞吴