您的位置:首页 > Web前端 > HTML5

H5 canvas实现客户端压缩图片上传

2017-04-26 15:51 856 查看
现在手机随随便便拍个照都是5、6MB,如果用户提交图片,即占服务器资源,上传速度又慢,影响用户体验度,所以一般都会对图片进行处理。

之前用php写过一个压缩图片程序,是先将图片上传到服务器之后,在服务器端进行压缩,效果不是很理想。

后来想想,还是决定要在客户端压缩,依靠H5的canvas来对图片在本地进行压缩处理,将图片处理成为base64编码,然后发送到后台,后台再做处理然后存储就好了(这样就是普通的post的提交了)。

这样比较友好些,无论是对服务器还是对用户。

html代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title>压缩上传为base64</title>
<script src="../src/jquery.min.js"></script>
</head>

<body >
<form id="form1" name="form1" method="post" action="">
<input type="file" name="fileToUpload" id="fileToUpload"/> <br />
<input type="text" name="compressValue" id="compressValue" style="display:none;" /><br/>
<input type="button" id='uploadBtn' value="上传" /><br/>
</form>
</body>
<script type="text/javascript">

//图片上传change事件
$('#fileToUpload').change(function(){
uploadBtnChange();
});

//提交click事件
$('#uploadBtn').click(function(){
var preview = document.getElementById('compressValue').value;
if(preview){
$.ajax({
url:"index.php",
type: "POST",
data:{'imgBase64':preview},
dataType:'json',
success:function(json) {
alert(json);
},
error:function(){
alert('操作失败,请跟技术联系');
}
});
}
});

function uploadBtnChange(){
var scope = this;
if(window.File && window.FileReader && window.FileList && window.Blob){
//获取上传file
var filefield = document.getElementById('fileToUpload'),
file = filefield.files[0];
//获取用于存放压缩后图片base64编码
var compressValue = document.getElementById('compressValue');
processfile(file,compressValue);
}else{
alert("此浏览器不完全支持压缩上传图片");
}
}

function processfile(file,compressValue) {
var reader = new FileReader();
reader.onload = function (event) {
var blob = new Blob([event.target.result]);
window.URL = window.URL || window.webkitURL;
var blobURL = window.URL.createObjectURL(blob);

baa3
var image = new Image();
image.src = blobURL;
image.onload = function() {
var resized = resizeMe(image);
compressValue.value = resized;
}
};
reader.readAsArrayBuffer(file);
}

function resizeMe(img) {
//压缩的大小
var max_width = 1920;
var max_height = 1080;

var canvas = document.createElement('canvas');
var width = img.width;
var height = img.height;
if(width > height) {
if(width > max_width) {
height = Math.round(height *= max_width / width);
width = max_width;
}
}else{
if(height > max_height) {
width = Math.round(width *= max_height / height);
height = max_height;
}
}

canvas.width = width;
canvas.height = height;

var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, width, height);
//压缩率
return canvas.toDataURL("image/jpeg",0.92);
}
</script>
</html>


php代码:

header('Content-type:text/html;charset=utf-8');
$base64_image_content = $_POST['imgBase64'];
//echo $base64_image_content;die;
//匹配出图片的格式
if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){
$type = $result[2];
$new_file = './upload/';

//如果文件不存在,则创建
if(!file_exists($new_file))
{
mkdir($new_file, 0777, true);
}

$new_file = $new_file.time(). '.' .$type;
if (file_put_contents($new_file, base64_decode(str_replace($result[1],'', $base64_image_content)))){
echo json_encode('上传成功!');
}else{
echo json_encode('上传失败!');
}
}


注意:

1、部分代码是参照网上的,安全性不能全部保证

2、运行index.html选择要上传的图片文件点击上传

3、必须配置安装在php服务器中使用,否则有些功能不能正常使用(但压缩图片不受影响)

4、仅支持主流及ie9以上浏览器,ie9以下请单独做处理。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  php 图片 压缩 canvas H5