jincon 发表于 2015-02-26 18:31:01 发表在: php开发
- 通常压缩图片需要上传到后端,由后端处理。
- 但是如果要上传的图片很大,特别是手机当场拍摄下来的照片(约2M+),那样效率会很低,用户也不会愿意等待。
- 现在能够由前端本地压缩的话,效率将会极大的提升。
这个玩意很强大的地方就在于他可以在HTML5 前端压缩 ,大大加快了上传速度,以及节约流量。
直接上写好的demo了
HTML
01 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" |
05 |
<title> New Document </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 |
var input = document.querySelector('input'); |
18 |
input.onchange = function () { |
19 |
lrz(this.files[0], {width: 100}, function (results) { |
20 |
// 你需要的数据都在这里,可以以字符串的形式传送base64给服务端转存为图片。 |
24 |
var xhr = new XMLHttpRequest(); |
26 |
base64: results.base64, |
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 |
var result = JSON.parse(xhr.response); |
35 |
? alert('服务端错误,未能保存图片') |
36 |
//: demo_report('服务端实存的图片', result.src, result.size); |
40 |
xhr.send(JSON.stringify(data)); // 发送base64 |
重要的是很多的人不知道这个工具是后端该如何处理,所以贴出php的代码:
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; |
10 |
$file=time().'.'.$ext; |
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