项目分享五:H5图片压缩与上传

1、简介

图片的压缩与上传,是APP里一个很经常使用的功能。咱们来年看 ChiTuStore 是怎样作的。相关文件 App/Module/User/UserInfo.html,App/Module/User/UserInfo.tshtml

 

2、HTML布局

HTML 文件中,有以下二句,第一句就是上图所看到的图片,其中的 class 表示该图片以圆形来显示,而且靠右。第二句是一个 Input 控件,其类型为 file ,是用来上传文件的。值得注意的是 style,这的做用是让该控件与图片重叠,而且透明(opacity:0),accept="image/*" 的做用是只上传图片。node

 <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/*">

 

3、图片的压缩

传统 WEB 的作法,都是把图片直接上传到服务端,而后在服务端进行压缩。但如今,在H5 中,是能够对图片进行压缩再上传的。咱们来看一下 JS 代码,其中的 ImageFileResize 就是用来处理图片的压缩的。git

    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。github

这几个对象、函数的具体用法,在这里就不展开说了,网上搜一下就能够找到答案了。web

 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);

    }

 

4、服务端的保存

服务的保存有两种方法canvas

一、把 base64 字符串转换为二进制流,而后再保存为图片文件。浏览器

二、直接把 base64 保存数据库。在这个项目,是把它保存到 MongoDB 数据库。app

 

5、浏览器的坑

即然是经过浏览器进行压缩上传,那么就没法避免会有坑。函数

一、在 QQ 浏览器中,不起做用。听说是不支持 canvas 。

二、在 APP 的混合开发中,在锤子 T2 的手机也不起做用。

 

6、小结

尽管在本地压缩、预览图片有着很好的用户体验,可是兼容性差,若是是 APP 的开发,仍是调用原生的接口吧。若是浏览器的 WEB APP 项目,仍是得考虑兼容性。不支持 canvas 的浏览器,使用传统的方法来上传图片。

 

代码已经开源在 github,感兴趣的朋友能够自行下载。https://github.com/ansiboy/ChiTuStore

 

项目分享四:购物车页面的更新 

项目分享三:页面之间的传值

项目分享二:APP 小红点中数字的处理

项目分享一:在项目中使用 IScroll 所碰到的那些坑

相关文章
相关标签/搜索