利用前端壓縮圖片 (js 搭配 php)
隨者手機相機的進步,現在手機拍出來的照片檔案越來越大,雖然現在iPhone出到了iPhone X
作者我手上只有iPhone 6s,隨便拍幾張照片,平均照片大小落在1.8M~2.5M為主
當然,最簡單的方法就是直接上傳原始檔案,不過今天要講解的是如何在前端先壓縮完再上傳,以節省網路流量及上傳時間。
本次一共會介紹兩種方法,第一種是利用js套件 (https://github.com/think2011/localResizeIMG)
index.html
upload.php
OK! 第一種方法結束了,非常簡單
第二種方法是利用HTML 5來進行壓縮
作者我手上只有iPhone 6s,隨便拍幾張照片,平均照片大小落在1.8M~2.5M為主
當然,最簡單的方法就是直接上傳原始檔案,不過今天要講解的是如何在前端先壓縮完再上傳,以節省網路流量及上傳時間。
本次一共會介紹兩種方法,第一種是利用js套件 (https://github.com/think2011/localResizeIMG)
index.html
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<script src="js/lrz.bundle.js"></script> | |
<script src="http://cdn.bootcss.com/jquery/2.2.4/jquery.min.js"></script> | |
</head> | |
<body> | |
<input id="img_input" type="file" accept="image/*" /> | |
<div id="preview_box"></div> | |
<script> | |
$("#img_input").on("change", function(e) { | |
var file = e.target.files[0]; //获取图片资源 | |
var filename = file.name; | |
// 只选择图片文件 | |
if (!file.type.match('image.*')) { | |
return false; | |
} | |
// LocalResizeIMG处理: | |
lrz(file, {width: 400}) | |
.then(function (rst) { | |
$.ajax({ | |
url: 'upload.php', | |
data: rst.formData, // LocalResizeIMG 直接封装好的 | |
processData: false, | |
contentType: false, | |
type: 'POST' | |
}).done(function(data, textStatus, jqXHR){ | |
// 图片预览 | |
var img = new Image(); | |
img.src = rst.base64; | |
img.onload = function () { | |
$("#preview_box").empty().append(img); | |
}; | |
}); | |
return rst; | |
}) | |
.catch(function (err) { | |
// 万一出错了,这里可以捕捉到错误信息 | |
// 而且以上的then都不会执行 | |
alert('ERROR:' + err); | |
}) | |
.always(function () { | |
// 不管是成功失败,这里都会执行 | |
}); | |
}); | |
</script> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
if ($error == UPLOAD_ERR_OK) { | |
$tmp_name = $_FILES["file"]["tmp_name"]; | |
$name = $_FILES["file"]["name"]; | |
move_uploaded_file($tmp_name, "$name"); | |
} | |
?> |
第二種方法是利用HTML 5來進行壓縮
留言
張貼留言