LocalResizeIMG前端HTML5本地压缩图片上传,兼容移动设备IOS,android
jincon发表于2015-02-2618:31:01发表在:php开发
localresizeimg-概述
通常压缩图片需要上传到后端,由后端处理。
但是如果要上传的图片很大,特别是手机当场拍摄下来的照片(约2M+),那样效率会很低,用户也不会愿意等待。
现在能够由前端本地压缩的话,效率将会极大的提升。
这个玩意很强大的地方就在于他可以在HTML5前端压缩,大大加快了上传速度,以及节约流量。
直接上写好的demo了
HTML
01 | <!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN" |
02 | "http://www.w3.org/TR/html4/loose.dtd"> |
05 | < title >NewDocument</ title > |
06 | < meta name = "Generator" content = "EditPlus" > |
07 | < meta name = "Author" content = "" > |
08 | < meta name = "Keywords" content = "" > |
09 | < meta name = "Description" content = "" > |
10 | < script src = "lrz.mobile.min.js" ></ script > |
15 | < input type = "file" capture = "camera" /> |
17 | varinput=document.querySelector('input'); |
18 | input.onchange=function(){ |
19 | lrz(this.files[0],{width:100},function(results){ |
20 | //你需要的数据都在这里,可以以字符串的形式传送base64给服务端转存为图片。 |
24 | varxhr=newXMLHttpRequest(); |
27 | size:results.base64.length//校验用,防止未完整接收 |
29 | xhr.open('POST','1.php'); |
30 | xhr.setRequestHeader('Content-Type','application/json;charset=utf-8'); |
31 | xhr.onreadystatechange=function(){ |
32 | if(xhr.readyState===4&&xhr.status===200){ |
33 | varresult=JSON.parse(xhr.response); |
36 | //:demo_report('服务端实存的图片',result.src,result.size); |
40 | xhr.send(JSON.stringify(data));//发送base64 |
重要的是很多的人不知道这个工具是后端该如何处理,所以贴出php的代码:
02 | $base64 = file_get_contents ( "php://input" );//获取输入流 |
03 | $base64 =json_decode( $base64 ,1); |
04 | $data = $base64 [ 'base64' ]; |
05 | preg_match( "/data:image\/(.*);base64,/" , $data , $res ); |
07 | if (!in_array( $ext , array ( "jpg" , "jpeg" , "png" , "gif" ))){ |
08 | echo json_encode( array ( "error" =>1)); die ; |
11 | $data =preg_replace( "/data:image\/(.*);base64,/" , "" , $data ); |
12 | if ( file_put_contents ( $file , base64_decode ( $data ))===false){ |
13 | echo json_encode( array ( "error" =>1)); |
15 | echo json_encode( array ( "error" =>0)); |
下载地址:
https://github.com/think2011/localResizeIMG3/releases
关键词:移动端上传图片,localresizeimg
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理