手记

100行代码写个前端压缩的js插件

2019-06-12 10:53:183385浏览

winlion

1实战 · 14手记 · 2推荐

最近开了一节课,《支持10万人同时在线 Go语言打造高并发web即时聊天(IM)应用

课程播出后,很多同学询问了前端图片压缩相关知识,有鉴于此,笔者整理了一个前端压缩的JS插件,老规矩,文章最末给源代码。目前貌似支持Jquery 啦

函数原型说明

function compress(file,options)

  • file对象即文件对象,对应filedom 的文件数组中的元素

  • options 是一个对象,包括参数如下

参数名称参数描述
maxwidth压缩后图片的最大宽度,int,默认400
maxheight压缩后图片的最大高度,int,默认400
threshold图片大小阈值,单位b,低于这个值将不压缩,int,默认102400
quality图片压缩质量

返回说明

支持promiss

  • success,function(base64data)类型函数,base64data代表文件的base64编码,包括头如data:image/png;base64,/ivxxxxxx

  • fail,function(errmsg)类型函数。errmsg出错原因

//js
compress(file,options).then(success,fail)

调用示例

<!--html-->
<input type="file" onchange="uploadandcompress(this)" />

//js
function uploadandcompress(dom){
               compress(dom.files[0],
               {"maxwidth":1200,"maxheight":1200}
).then(
res=>{console.log(res)},
res=>{console.log(res)})
}

效果演示

获得代码

关注公众号betaidea ,回复前端压缩即可获得


1人推荐
随时随地看视频
慕课网APP