文件上传前压缩图片尺寸大小,支持安卓微信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 = $('');

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

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

        $fileInput.click();
    });

你可能感兴趣的:(图片压缩,android,微信开发,html5,javascript)