DropZone插件实现图片压缩

 1  transformFile: function(file, done) {
 2      //如果不超过2M直接上传
 3      if (file.size < 2048 * 1000) return done(file);
 4  
 5      //这里的File对象继承自Blob,
 6      //当执行到这里的时候File不一定加载完
 7      //所以需要再加载一次,回调中进行压缩
 8      var reader = new FileReader();
 9      reader.addEventListener("loadend",
10      function() {
11          // 压缩图片大小
12          var img = new Image();
13          img.onload = function() {
14              var cvs = document.createElement('canvas');
15              cvs.width = img.naturalWidth;
16              cvs.height = img.naturalHeight;
17  
18              var ctx = cvs.getContext("2d").drawImage(img, 0, 0);
19  
20              var zipImg = cvs.toDataURL("image/jpeg", 70 / 100);
21              console.log(zipImg);
22              return done(Dropzone.dataURItoBlob(zipImg));
23          };
24          img.src = reader.result;
25      });
26      reader.readAsDataURL(file);
27  }

 

posted @ 2018-02-06 13:43  vongzh  阅读(346)  评论(0编辑  收藏