| 
                                             一、简介 图片的压缩与上传,是APP里一个很常用的功能。我们来年看 ChiTuStore 是怎样做的。相关文件 App/Module/User/UserInfo.html,App/Module/User/UserInfo.ts 
 
 二、HTML布局 HTML 文件中,有如下二句,第一句就是上图所看到的图片,其中的 class 表示该图片以圆形来显示,并且靠右。第二句是一个 Input 控件,其类型为 file ,是用来上传文件的。值得注意的是 style,这的作用是让该控件与图片重叠,并且透明(opacity:0),accept="image/*" 的作用是只上传图片。 
 
  <img data-bind="attr:{src:userInfo.HeadImageUrl}" class="img-circle pull-right" style="width:70px;height:70px;">  <input type="file" style="position:absolute;top:0px;left:0px;opacity:0;width:100%;height:90px;" accept="image/*">   三、图片的压缩 传统 WEB 的做法,都是把图片直接上传到服务端,然后在服务端进行压缩。但现在,在H5 中,是可以对图片进行压缩再上传的。我们来看一下 JS 代码,其中的 ImageFileResize 就是用来处理图片的压缩的。 
 
 复制代码     page.viewChanged.add(() => {         var e = page.nodes().content.querySelector('[type="file"]');         var imageFileResize = new ImageFileResize(<HTMLInputElement>e, { maxWidth: 100, maxHeight: 100 });         imageFileResize.imageResized = (urls: string[], thumbs1: string[], thumbs2: string[]) => {             model.userInfo.HeadImageUrl(thumbs1[0]);             member.setUserInfo(mapping.toJS(model.userInfo));         }         ko.applyBindings(model, page.node());     }) 复制代码 我们现在来看一下 ImageFileResize 中的关键代码,这段代码的作用是用来把 <input type="file"/> 选取的文件,进行压缩的。其中有几个关键的对象、函数,是 H5 中的 API,FileReader,createObjectURL,Image。 
 
 这几个对象、函数的具体用法,在这里就不展开说了,网上搜一下就可以找到答案了。 
 
 复制代码  var reader = new FileReader();  reader.readAsArrayBuffer(file);  reader.onload = (ev: Event) => {       var blob = new Blob([event.target['result']]);       window['URL'] = window['URL'] || window['webkitURL'];       var blobURL = window['URL'].createObjectURL(blob); // and get it's URL       var image = new Image();       image.src = blobURL;       image.onload = () => {            var url = this.resizeMe(image, max_width, max_height);            var thumb = this.resizeMe(image, this.thumb2.maxWidth, this.thumb2.maxHeight);            result.resolve({ index: index, url: url, data: url, thumb: thumb });       }  } 复制代码 下面我们再来看一下 resizeMe 函数,这个函数的把的图片(HTMLImageElement),转换为了 base64 的字符串,其中一个重要的对象就是 canvas,它也是 H5 中的对象。通过它可以把图片转换为 base64 字符串。 
 
 复制代码  private resizeMe(img: HTMLImageElement, max_width: number, max_height: number) { 
 
         var canvas = document.createElement('canvas'); 
 
         var width: number = img.width;         var height: number = img.height; 
 
         // calculate the width and height, constraining the proportions         if (width > height) {             if (width > max_width) {                 height = Math.round(height *= max_width / width);                 width = max_width;             }         } else {             if (height > max_height) {                 width = Math.round(width *= max_height / height);                 height = max_height;             }         } 
 
         canvas.width = width;         canvas.height = height;         var ctx = canvas.getContext("2d");         ctx.drawImage(img, 0, 0, width, height); 
 
         return canvas.toDataURL("image/jpeg", 0.7); 
 
     } 复制代码   四、服务端的保存 服务的保存有两种方法 
 
 1、把 base64 字符串转换为二进制流,然后再保存为图片文件。 
 
 2、直接把 base64 保存数据库。在这个项目,是把它保存到 MongoDB 数据库。 
 
   五、浏览器的坑 即然是通过浏览器进行压缩上传,那么就无法避免会有坑。 
 
 1、在 QQ 浏览器中,不起作用。据说是不支持 canvas 。 
 
 2、在 APP 的混合开发中,在锤子 T2 的手机也不起作用。 
 
   六、小结 尽管在本地压缩、预览图片有着很好的用户体验,但是兼容性差,如果是 APP 的开发,还是调用原生的接口吧。如果浏览器的 WEB APP 项目,还是得考虑兼容性。不支持 canvas 的浏览器,使用传统的方法来上传图片。 
 
   
 
 代码已经开源在 github,感兴趣的朋友可以自行下载。https://github.com/ansiboy/ChiTuStore 
  
                                         |