之前手機微信端的項目因為圖片太大導致體驗十分不流暢,后來采用把上傳的圖片統一壓縮大小后解了燃眉之急。
但這個方法的遺憾就是得等到圖片上傳后在服務器端壓縮,用戶如果上傳比較大的圖片耗時太大,而且也耗流量。
關鍵是在用戶上傳前就把圖片壓縮了,如今找到了解決方法;
用了lrz這個庫,http://www.jq22.com/jquery-info3419,感謝這個地址
平常手機照片2M的圖一般能壓縮到150kb左右,效果明顯
首先引入三個庫文件
<script type="text/javascript" src="__TMPL__Vote/assets/js/mobileFix.mini.js" ></script> <script type="text/javascript" src="__TMPL__Vote/assets/js/exif.js" ></script> <script type="text/javascript" src="__TMPL__Vote/assets/js/lrz.js" ></script>
根據項目的不同使用不同的引入地址
<input id="uploaderFile0" name="img[]" type="file" data-add="0" onchange="changeFile(this)"/>
input:file框中使用時間onchang來觸發壓縮
var input = document.querySelector('input'); lrz(obj.files[0], {width: 350}, function (results) { // 你需要的數據都在這里,可以以字符串的形式傳送base64給服務端轉存為圖片。 console.log(results); $("#img64base").val(results.base64); $(obj).remove(); });
壓縮后是base64字符串,把該字符串放到一個隱藏的input里,提交時只提交該字符串,刪除input:file;
<input type="hidden" name="img64base[]" id="img64base0" value="" />
多文件提交的是數組img64base
php對傳過來的字符串處理如下(多文件)
if($_POST['img64base'][0] !=""){ //保存base64字符串為圖片 //匹配出圖片的格式 foreach($_POST['img64base'] as $k=>$v){ if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $v, $result)){ $type = $result[2]; $name=$this->fast_uuid();//圖片的命名函數 $new_file = "Public/Mun/vote/{$name}.{$type}"; if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $v)))){ //echo '新文件保存成功:', $new_file; $data['add_img'][$k] = $name.'.'.$type; } } } $_POST['img']=implode(',',$data['add_img']); }else{ //$_POST['img']=""; $this->error('至少上傳一張圖片!'); }
注意這個地方就能看懂
上傳過來的字符串前面多了data:image/jpeg;base64, 這幾個字,去掉之后才能使用base64_decode函數轉換成圖片內容,然后用file_put_contents函數把圖片能容放進一個圖片文件里,注意圖片的后綴名也是從data:image/jpeg;base64中獲取的;
fast_uuid()是圖片的命名函數,從網上找的,如下
/* * 參數 suffix_len指定 生成的 ID 值附加多少位隨機數,默認值為 3。 * 感謝“Ivan Tan|譚俊青 DrinChing (at) Gmail.com”提供的算法。 * @param int suffix_len * @return string */ private function fast_uuid($suffix_len=3){ //! 計算種子數的開始時間 $being_timestamp = time(); $time = explode(' ', microtime()); $id = ($time[1] - $being_timestamp) . sprintf('%06u', substr($time[0], 2, 6)); if ($suffix_len > 0) { $id .= substr(sprintf('%010u', mt_rand()), 0, $suffix_len); } return $id; }