Dropzone.js 上传图片压缩

Dropzone.js的使用:https://www.blyoo.com/4989.html


var myDropzone = new Dropzone("#myAwesomeDropzone", {
        //...此处省略部分代码...
        transformFile: function(file, done) {
             //如果一开始没有对文件格式进行限制,需要加上这一句的,不然上传的非图片格式文件会报错
            //判断上传的文件是不是图片,如果不是图片直接上传
            if (file.type.indexOf('image') == -1) return done(file);
            
            //如果不超过2M直接上传
            if (file.size < 2048 * 1000) return done(file);

            //这里的File对象继承自Blob,
            //当执行到这里的时候File不一定加载完
            //所以需要再加载一次,回调中进行压缩
            var reader = new FileReader();
            reader.addEventListener("loadend",
                function() {
                    // 压缩图片大小
                    var img = new Image();
                    img.onload = function() {
                        var cvs = document.createElement('canvas');
                        cvs.width = img.naturalWidth;
                        cvs.height = img.naturalHeight;

                        var ctx = cvs.getContext("2d").drawImage(img, 0, 0);

                        var zipImg = cvs.toDataURL("image/jpeg", 70 / 100);
                        console.log(zipImg);
                        return done(Dropzone.dataURItoBlob(zipImg));
                    };
                    img.src = reader.result;
                });
            reader.readAsDataURL(file);
        }
        //...此处省略部分代码...
    })

参考:

https://www.cnblogs.com/vongzh/p/8421975.html

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注




Enter Captcha Here :