文件上传前紧缩图片尺寸大小,支撑安卓微信APP浏览器

    function ImageFileResize(file, maxWidth, maxHeight, callback) {
        var Img = new Image;
        var canvas = document.createElement('canvas');
        var ctx = canvas.getContext('2d');

        Img.onload = function() {
            if (Img.width>maxWidth || Img.height>maxHeight) {
                var bili = Math.max(Img.width/maxWidth, Img.height/maxHeight);
                canvas.width = Img.width/bili;
                canvas.height = Img.height/bili;
            }else{
                canvas.width = Img.width;
                canvas.height = Img.height;
            }
            ctx.drawImage(Img, 0, 0, Img.width, Img.height, 0, 0, canvas.width, canvas.height);

//            $('body').append(canvas);
            callback(canvas.toDataURL());
        };

        try{
            Img.src = window.URL.createObjectURL(file);
        }catch(err){
            try{
                Img.src = window.webkitURL.createObjectURL(file);
            }catch(err){
                alert(err.message);
            }
        }
    }

    $('.js-uploader').on('click', function () {
        var $clickObj = $(this);
        var $fileInput = $('<input type="file"/>');

        $fileInput.on('change',function () {
            $clickObj.text('正在上传...');

            ImageFileResize($fileInput[0].files[0], 800, 800, function (dataUrl) {
                $.ajax({
                    type: "POST",
                    url: "<?=$this->createMobileUrl('Upload')?>",
                    data: {imgDatUrl:dataUrl},
                    success : function (ret) {
                        $clickObj.prev().remove();
                        $clickObj.before("<img src=\"" + dataUrl + "\"/> ");
                        $clickObj.next().val(ret.path);
                        $clickObj.text('从新上传');
                    },
                    dataType : "json"
                });
            });
        });

        $fileInput.click();
    });
    原文作者:王道中强流
    原文地址: https://segmentfault.com/a/1190000002769740
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞