惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Hacker News - Newest:
Hacker News - Newest: "LLM"
NISL@THU
NISL@THU
Know Your Adversary
Know Your Adversary
The Hacker News
The Hacker News
D
Docker
Scott Helme
Scott Helme
有赞技术团队
有赞技术团队
罗磊的独立博客
A
Arctic Wolf
P
Privacy International News Feed
Google DeepMind News
Google DeepMind News
Spread Privacy
Spread Privacy
B
Blog
A
About on SuperTechFans
L
LINUX DO - 最新话题
博客园 - 司徒正美
T
The Blog of Author Tim Ferriss
P
Proofpoint News Feed
W
WeLiveSecurity
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Google DeepMind News
Google DeepMind News
aimingoo的专栏
aimingoo的专栏
T
The Exploit Database - CXSecurity.com
美团技术团队
J
Java Code Geeks
Cloudbric
Cloudbric
雷峰网
雷峰网
Vercel News
Vercel News
P
Proofpoint News Feed
Webroot Blog
Webroot Blog
Security Archives - TechRepublic
Security Archives - TechRepublic
人人都是产品经理
人人都是产品经理
Martin Fowler
Martin Fowler
G
Google Developers Blog
T
Tenable Blog
PCI Perspectives
PCI Perspectives
Engineering at Meta
Engineering at Meta
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
H
Hackread – Cybersecurity News, Data Breaches, AI and More
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园_首页
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Apple Machine Learning Research
Apple Machine Learning Research
C
Cybersecurity and Infrastructure Security Agency CISA
S
Secure Thoughts
N
News and Events Feed by Topic
GbyAI
GbyAI
S
SegmentFault 最新的问题
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org

博客园 - 麦舒

网站访问速度的优化 ERP 订单打印的优化 页面 SEO 信息的优化 一个网站首页重构小记 广告播放软件的开发 项目分享九:客户端的异常处理 项目分享八:基于按钮点击事件的弹窗 项目分享七:客户端防止表单重复提交 项目分享六:图片的延迟加载 项目分享四:购物车页面的更新 项目分享三:页面之间的传值 项目分享二:APP 小红点中数字的处理 项目分享一:在项目中使用 IScroll 所碰到的那些坑 微信开发——通过授权获取用户的基本信息 千呼万唤岂出来,写款软件不容易——Visual Entity 2.0 发布 实现虽易,写好不易——小玩意也能体现编码功力,微信消息处理框架发布 代码重构之 —— 一堆if、esle 逻辑的处理 ALinq Dynamic 使用指南——慨述(上) ALinq Dynamic 使用指南——代码的获取与编译
项目分享五:H5图片压缩与上传
麦舒 · 2015-12-17 · via 博客园 - 麦舒

2015-12-17 15:27  麦舒  阅读(33039)  评论()    收藏  举报

一、简介

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

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

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

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

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