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

本文介绍了一个JavaScript函数,用于实现图片文件的实时压缩处理,并通过Ajax技术将压缩后的图片上传到服务器。具体步骤包括读取文件、按指定尺寸压缩图片、使用Canvas进行绘图并转换为Base64编码的数据URL格式,最后通过POST请求发送到服务器。
    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();
    });
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值