猿问

关于客户端JS能否等比例压缩图片的请教

当用户通过浏览器上传图片时,不管用户用了多大的图片,都使其能够上传,现在想用JS先在浏览器上对图片进行压缩处理,然后上传,而不是将整个图片上传到后台服务器然后在压缩后存储。请问这种方案是否可行?新浪微博在上传图片的时候是怎样一种解决方案?请各路大牛不吝赐教!谢谢。

小怪兽爱吃肉
浏览 779回答 7
7回答

跃然一笑

<script language="JavaScript" type="text/javascript">&nbsp;function DrawImage(ImgD,FitWidth,FitHeight)&nbsp;{&nbsp;var image=new Image();&nbsp;image.src=ImgD.src;&nbsp;&nbsp; &nbsp; if(image.width>0 && image.height>0)&nbsp;&nbsp; &nbsp; {&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; if(image.width>FitWidth)&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ImgD.width=FitWidth;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ImgD.height=(image.height*FitWidth)/image.width;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(ImgD.height>FitHeight)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ImgD.height=FitHeight;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ImgD.width=(image.width*FitHeight)/image.height;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; else if(image.height>FitHeight)&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ImgD.height=FitHeight;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ImgD.width=(image.width*FitHeight)/image.height;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(image.width>FitWidth)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ImgD.width=FitWidth;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ImgD.height=(image.height*FitWidth)/image.width;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; else&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ImgD.width=image.width;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ImgD.height=image.height;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp;&nbsp; &nbsp; }&nbsp;}&nbsp;</script>最近做一个页面时用到的,不知道符不符合你的需求!

ABOUTYOU

也可以考虑用flash去实现压缩上传的功能

小唯快跑啊

python的话,直接用PIL在服务器端处理就可以了,没必要做在客户端用js做

守着一只汪

客户端的js改变图片的宽度和高度 是很难做到效果漂亮的,大部分情况都是服务器端语言压缩的

缥缈止盈

关于JS前端图片压缩 这里有详细的方案http://www.imwinlion.com/archives/158摘录一段如下,应该是你想要的这个场景的难点在于图片压缩,为什么是图片前端压缩?首先,因为当前用户基本上是大屏手机,一个图1-4M,是很正常的,但是用户参与活动的时候,未必愿意花这个流量,这样这个活动关上传图片这一步,就会降低很多用户参与的欲望了。其次,用户的网络状态未必很好,虽然用户3G很普遍,4G成规模,WIFI热点也很多,但是上传这么大的一张图,以2M估算,每秒上传速度100KB,也要20秒,难保这20秒时间网络不出任何差错。再次,用户未必愿意等待这么长的时间。解决方案在哪里?,答案是前端压缩,这里笔者常用的插件是lrz下载地址如下,也给个demo
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答