Shelton

使用localResizeIMG前端图片压缩

localResizeIMG前端图片压缩

起因

前段时间写了个小项目,涉及到图片上传压缩这块,然后google相关资料,发现了一个很好的开源图片压缩localResizeIMG,便决定把前端和后端相关代码贴出来方便以后使用!
localResizeIMG项目:https://github.com/think2011/localResizeIMG

说明

localResizeIMG插件会把图片转化为base64编码,当然你也可以把base64转化为本地图片进行保存。
这里我将直接把base64存入数据库不保存为图片文件,关于base64编码更多内容可以参考http://liming.it/blog/2014/04/08/image-base64-encode-and-decode-using-php/
下面代码我将使用:

bootstrap
新浪SAE
php

代码中的js与css样式请自行下载导入

展示

选择图片前:

选择图片后:

前端代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>上传图片</title>
<!-- Bootstrap -->
<link href="assets/css/upload.css" rel="stylesheet">
<link href="assets/css/bootstrap.min.css" rel="stylesheet">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div>
<div style="width:100%; text-align:center" id="upload_container" class="container-fluid" >
<h2 style="color:#111">请上传照片</h2>
<progress value="0" max="100"></progress> <br />
<table >
<!-- <center><input id="upload_file" type="file" accept="image/*" /></center> <br /> <br /> -->
<a href="javascript:;" class="file">选择文件
<input type="file" name="" id="upload_file" accept="image/*">
</a> <br /> <br />
<span style="color:#F00" id="status">选择图片后,图片显示即可上传! </span> <br /> <br />
<button type="button" class="btn btn-danger" id="btn">上传</button> <br />
<p id="info" style="text-align: center"></p>
</table>
</div>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="assets/js/jquery-1.11.3.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="assets/js/bootstrap.min.js"></script>
<script src="assets/js/lrz.bundle.js"></script>
<script src="assets/js/upload-pic.js"></script>
</body>
</html>

JS代码

upload-pic.js文件代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
var isShow = false;
$div = document.getElementById("upload_container");
var status_text = document.getElementById("status");
var info_text = document.getElementById("info");
var btn = document.getElementById('btn');
btn.style.visibility = "hidden"; //先隐藏上传按钮
document.querySelector('#upload_file').addEventListener('change', function () {
progress = document.querySelector('progress');
// this.files[0] 是用户选择的文件
var that = this;
lrz(that.files[0], {width: 500}, {height: 500})
.then(function (rst) {
// 把处理的好的图片给用户看
// 重新加载图片时,remove 原来的img 对象(为了防止用户重新选择图片)
if ($('img').length > 0) {
$('img').remove();
}
var img = new Image();
img.src = rst.base64;
var sourceSize = toFixed2(that.files[0].size / 1024);
var resultSize = toFixed2(rst.fileLen / 1024);
var scale = parseInt(100 - (resultSize / sourceSize * 100));
info_text.innerHTML = "压缩前的文件大小: " + sourceSize + "KB" +
"<br />" + "压缩后的文件大小: " + resultSize + "KB" + "<br />"
+ "省了: " + scale + "%";
img.onload = function () {
$div.appendChild(img);
progress.value = 0;
btn.style.visibility = "visible"; //当图片加载在页面上显示上传按钮
isShow = true; //当图片加载在页面上才能上传
status_text.innerHTML = "请上传图片!";
};
return rst;
});
});
function toFixed2 (num) {
return parseFloat(+num.toFixed(2)); //toFixed(2),保留两位小数
}
/*上传按钮*/
$('#btn').click(function () {
// 获取file对象并检测是否加载完图片
if (isShow == true && $('img').length >0) {
status_text.innerHTML = "正在为你压缩、上传图片中!";
var selectedFile = $('#upload_file').get(0).files[0];
lrz(selectedFile, {width: 500}, {height: 500})
.then(function (rst) {
// 这里该上传给后端啦
/* ==================================================== */
// 原生ajax上传代码,所以看起来特别多 ╮(╯_╰)╭,但绝对能用
// 其他框架,例如jQuery处理formData略有不同,请自行google,baidu。
var xhr = new XMLHttpRequest();
/* var data = {
base64: rst.base64,
};
*/
xhr.open('POST', '/upload_info.php'); //这里填写你要上传的服务器
xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
xhr.onload = function () {
if (xhr.status === 200) {
// 上传成功
status_text.innerHTML = "上传成功";
// $div.appendChild(status);
// progress.value = 0;
// alert("2秒后跳转到个人信息页面!");
setTimeout(window.location.href='show_pic.php', 5);
// 此处上传成功后跳转到相应页面
} else {
// 处理其他情况
}
};
xhr.onerror = function () {
// 处理错误
};
xhr.upload.onprogress = function (e) {
// 上传进度
progress.value = ((e.loaded / e.total) || 0) * 100;
};
// 添加参数
// rst.formData.append('fileLen', rst.fileLen);
// rst.formData.append('xxx', '我是其他参数');
// 触发上传
xhr.send(rst.base64);
/* ==================================================== */
isShow= false; //已上传完成,不可再上传。
return rst;
})
.catch(function (err) {
// 万一出错了,这里可以捕捉到错误信息
// 而且以上的then都不会执行
alert(err);
})
.always(function () {
// 不管是成功失败,这里都会执行
});
} else {
alert("请在图片压缩、加载完成后才上传!");
}
});

CSS代码

按钮CSS,upload.css文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
.file {
width: 140px;
position: relative;
display: inline-block;
background: #D0EEFF;
border: 1px solid #99D3F5;
border-radius: 4px;
padding: 4px 12px;
overflow: hidden;
color: #1E88C7;
text-decoration: none;
text-indent: 0;
line-height: 20px;
}
.file input {
position: absolute;
font-size: 100px;
right: 0;
top: 0;
opacity: 0;
}
.file:hover {
background: #AADFFD;
border-color: #78C3F3;
color: #004974;
text-decoration: none;
}
.btn {
width: 210px;
}

php后台

由于localResizeIMG把图片转化为base64编码,因此后台获取到的是base64编码数据,可直接用于<img/>中的src。 到时前台可直接用<img/>标签显示,如:<img src="$img_data" />

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<?
// SAE数据库连接参数
$host = SAE_MYSQL_HOST_M;
$port = SAE_MYSQL_PORT;
$user = SAE_MYSQL_USER;
$pwd = SAE_MYSQL_PASS;
$dbname = SAE_MYSQL_DB;
// 获取base64图片
$img_data = file_get_contents("php://input");
$conn = new mysqli($host, $user, $pwd, $dbname, $port);
$conn -> query("set names utf8");
if ($conn -> connect_error) {
echo "Falid to connect to MySQL!" . $conn -> connect_error;
exit;
}
$modify = $conn -> query("UPDATE juba_user SET pic='$img_data'");
if ($modify) {
// echo "<script>alert('成功上传!');location.href='show_pic.php';</script>";
}
$result -> free();
$conn -> close();
?>

若想把base64转为图片文件,添加如下代码即可

1
2
3
4
5
6
7
if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $img, $result)) { //先确认图片文件
$type = $result[2];
$name = time() . '_' . mt_rand() .".{$type}";
$new_file = "./Uploads/" . $name;//文件夹位置
file_put_contents($new_file, base64_decode(str_replace($result[1], '', $img)));
//$result[1] 相当于data:image/图片格式;base64,
}

最后

献上有关大神们相关localResizeIMG的网页!

移动端图片上传解决方案localResizeIMG先压缩后ajax无刷新上传
移动端图片上传解决方案localResizeIMG先压缩后ajax无刷新上传
LocalResizeIMG前端HTML5本地压缩图片上传,兼容移动设备IOS,android

Enjoy it!