这个玩意很强大的地方就在于他可以在HTML5 前端压缩 ,大大加快了上传速度,以及节约流量。
直接上写好的demo了
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <title> New Document </title>
- <meta name="Generator" content="EditPlus">
- <meta name="Author" content="">
- <meta name="Keywords" content="">
- <meta name="Description" content="">
- <script src="lrz.mobile.min.js"></script>
- </head>
- <body>
- <input type="file" capture="camera" />
- <script>
- var input = document.querySelector('input');
- input.onchange = function () {
- lrz(this.files[0], {width: 100}, function (results) {
- // 你需要的数据都在这里,可以以字符串的形式传送base64给服务端转存为图片。
- console.log(results);
- // 发送到后端
- var xhr = new XMLHttpRequest();
- var data = {
- base64: results.base64,
- size: results.base64.length // 校验用,防止未完整接收www.bcty365.com
- };
- xhr.open('POST', '1.php');
- xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
- xhr.onreadystatechange = function () {
- if (xhr.readyState === 4 && xhr.status === 200) {
- var result = JSON.parse(xhr.response);
- result.error
- alert('服务端错误,未能保存图片')
- //: demo_report('服务端实存的图片', result.src, result.size);
- : alert('上传OK');
- }
- };
- xhr.send(JSON.stringify(data)); // 发送base64
- });
- }
- </script>
- </body>
- </html>
重要的是很多的人不知道这个工具是后端该如何处理,所以贴出php的代码:
- <?php
- $base64=file_get_contents("php://input"); //获取输入流
- $base64=json_decode($base64,1);
- $data = $base64['base64'];
- preg_match("/data:image\/(.*);base64,/",$data,$res);
- $ext = $res[1];
- if(!in_array($ext,array("jpg","jpeg","png","gif"))){
- echo json_encode(array("error"=>1));die;
- }
- $file=time().'.'.$ext;
- $data = preg_replace("/data:image\/(.*);base64,/","",$data);
- if (file_put_contents($file,base64_decode($data))===false) {
- echo json_encode(array("error"=>1));
- }else{
- echo json_encode(array("error"=>0));
- }
下载地址:
https://github.com/think2011/localResizeIMG3/releases