H5图片压缩与上传

一、简介

图片的压缩与上传,是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 数据库。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值