壓縮部分是從網上搞下來的,上傳部分是本身寫的,至關於在其餘人的基礎上完善了這個壓縮上傳流程。javascript
壓縮部分,壓縮率通常,重在瀏覽器支持方面好些,使用了FileReader和Canvas實現,FileReader瀏覽器支持方面還不錯:
php
上傳部分,使用XMLHttpRequest上傳Blob實現,瀏覽器方面比FileReader差一點,不過也差不了多少,主要在安卓瀏覽器方面差一些:
html
大概根據上圖總結能支持到IE10及以上版本、大多數現代瀏覽器及多數安卓與ios瀏覽器。java
爲了保持ie瀏覽器儘可能向下支持,因此用的方法不算太多,壓縮比可能對比其餘壓縮插件不大。
開發時爲了方便,插件須要jQuery支持,插件須要放在jQuery以後加載。jquery
使用方法:ios
若是上傳時提示上傳失敗,檢查上傳地址是否正確而且控制檯提示Access-Control-Allow-Origin啥啥的就是服務接收段須要容許跨域,例如php須要加上
header( "Access-Control-Allow-Origin:*" );
下面是源碼
html頁面:git
<!doctype html> <html> <head> <meta charset="utf-8"> <title>圖片壓縮上傳</title> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script> <script src="UploadPic.js"></script> </head> <body> <input id="files" type="file" accept="image/*;capture=camera" class="input"> </body> </html>
UploadPic.js:json
$("#files").ready(UploadPic_init);//框件初始加載與綁定 /** * 初始化UploadPic * @constructor */ function UploadPic_init() { UploadPic.prototype.url = '';//初始上傳url var u = new UploadPic(); u.init({ input: document.querySelector("#files"),//框件綁定 callback: function (base64) { var _this=this; //獲取圖片類型 var typ = base64.match(/data:image\/([^\"]*)\;base64/); //base64 轉 blob var ccBlob= _this._getBlobBydataURI(base64,'image/'+typ[1]); if(ccBlob.size>_this.fileSize){ ccBlob=_this.input.files[0]; } var formData = new FormData(); var filname="file_"+_this.fileName+"."+typ[1]; formData.append("files", ccBlob ,filname); //組建XMLHttpRequest 上傳文件 var request = new XMLHttpRequest(); //上傳鏈接地址 request.open("POST", _this.url); request.onreadystatechange=function() { if (request.readyState==4) { if(request.status==200){ console.log(request.response); _this.uploadResult(request.response); _this.emptyFile(); }else{ alert("上傳失敗,檢查上傳地址是否正確"); _this.emptyFile(); } } } request.send(formData); }, loading: function () { } }); } /** * UploadPic * 初始化配置 init * 自定義文件框架change動做 changeAction * 自定義上傳結果動做 uploadResult */ function UploadPic() { this.isrun=0; this.sw = 0; this.sh = 0; this.tw = 0; this.th = 0; this.scale = 0; this.maxWidth = 0; this.maxHeight = 0; this.maxSize = 0; this.fileSize = 0; this.fileDate = null; this.fileType = ''; this.fileName = ''; this.input = null; this.canvas = null; this.mime = {}; this.type = ''; this.callback = function () {}; this.loading = function () {}; } /** * 初始化 */ UploadPic.prototype.init = function (options) { this.maxWidth = options.maxWidth || 1080;//圖片最大寬度 this.maxHeight = options.maxHeight || 1024;//圖片最大高度 this.maxSize = options.maxSize || 50 * 1024 * 1024;//圖片限制大小 this.input = options.input; this.mime = {'png': 'image/png', 'jpg': 'image/jpeg', 'jpeg': 'image/jpeg', 'bmp': 'image/bmp'}; this.callback = options.callback || function () {}; this.loading = options.loading || function () {}; this.url = this.url? this.url : "http://127.0.0.1/upload.php"; this._addEvent();//綁定change事件 }; /** * @description 綁定事件 * @param {Object} elm 元素 * @param {Function} fn 綁定函數 */ UploadPic.prototype._addEvent = function () { var _this = this; function tmpSelectFile(ev) { var icontinue=_this.changeAction();//自定義change事件 if(!icontinue){return;} _this._handelSelectFile(ev.target.files[0]); } this.input.addEventListener('change', tmpSelectFile, false); }; /** * @description 加載圖片 * @param {Object} ev 元素 * */ UploadPic.prototype._handelSelectFile = function (ev) { var file = ev; try{ this.type = file.type; }catch(e){ this.isrun=0; this.emptyFile(); return; } // 若是沒有文件類型,則經過後綴名判斷(解決微信及360瀏覽器沒法獲取圖片類型問題) if (!this.type) { this.type = this.mime[file.name.match(/\.([^\.]+)$/i)[1]]; } if (!/image.(png|jpg|jpeg|bmp)/.test(this.type)) { alert('選擇的文件類型不是圖片'); return; } if (file.size > this.maxSize) { alert('選擇文件大於' + this.maxSize / 1024 / 1024 + 'M,請從新選擇'); return; } this.fileName = this._muuid(); this.fileSize = file.size; this.fileType = this.type; this.fileDate = file.lastModifiedDate; this._readImage(file); }; /** * @description 讀取圖片文件 * @param {Object} image 圖片文件 */ UploadPic.prototype._readImage = function (file) { var _this = this; function tmpCreateImage(uri) { _this._createImage(uri); } this.loading(); this._getURI(file, tmpCreateImage); }; /** * @description 經過文件得到URI * @param {Object} file 文件 * @param {Function} callback 回調函數,返回文件對應URI * return {Bool} 返回false */ UploadPic.prototype._getURI = function (file, callback) { try{ var reader = new FileReader(); }catch(e){ alert('圖片上傳失敗,請升級瀏覽器'); return; } var _this = this; function tmpLoad() { // 頭不帶圖片格式,需填寫格式 var re = /^data:base64,/; var ret = this.result + ''; if (re.test(ret)) ret = ret.replace(re, 'data:' + _this.mime[_this.fileType] + ';base64,'); callback && callback(ret); } reader.onload = tmpLoad; reader.readAsDataURL(file); return false; }; /** * @description 建立圖片 * @param {Object} image 圖片文件 */ UploadPic.prototype._createImage = function (uri) { var img = new Image(); var _this = this; function tmpLoad() { _this._drawImage(this); } img.onload = tmpLoad; img.src = uri; }; /** * @description 建立Canvas將圖片畫至其中,並得到壓縮後的文件 * @param {Object} img 圖片文件 * @param {Number} width 圖片最大寬度 * @param {Number} height 圖片最大高度 * @param {Function} callback 回調函數,參數爲圖片base64編碼 * return {Object} 返回壓縮後的圖片 */ UploadPic.prototype._drawImage = function (img, callback) { this.sw = img.width; this.sh = img.height; this.tw = img.width; this.th = img.height; this.scale = (this.tw / this.th).toFixed(2); if (this.sw > this.maxWidth) { this.sw = this.maxWidth; this.sh = Math.round(this.sw / this.scale); } if (this.sh > this.maxHeight) { this.sh = this.maxHeight; this.sw = Math.round(this.sh * this.scale); } this.canvas = document.createElement('canvas'); var ctx = this.canvas.getContext('2d'); this.canvas.width = this.sw; this.canvas.height = this.sh; ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, this.sw, this.sh); this.callback(this.canvas.toDataURL(this.type)); ctx.clearRect(0, 0, this.tw, this.th); this.canvas.width = 0; this.canvas.height = 0; this.canvas = null; }; /** * 根據base64 內容 取得 bolb */ UploadPic.prototype._getBlobBydataURI = function (dataURI,type) { var binary = atob(dataURI.split(',')[1]); var array = []; for(var i = 0; i < binary.length; i++) { array.push(binary.charCodeAt(i)); } return new Blob([new Uint8Array(array)], {type:type }); }; /** * 生成uuid */ UploadPic.prototype._muuid = function () { var s = []; var hexDigits = "0123456789abcdef"; for (var i = 0; i < 36; i++) { s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1); } s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010 s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01 s[8] = s[13] = s[18] = s[23] = "-"; var uuid = s.join(""); return uuid; }; /** * 清空file */ UploadPic.prototype.emptyFile = function () { var file = $("#"+this.input.id); file.after(file.clone().val("")); file.remove(); this.input=document.querySelector("#"+this.input.id); file.ready(this._addEvent()); }; /** * 自定義文件框件change動做 */ UploadPic.prototype.changeAction = function () { if(this.isrun==0){ this.isrun=1; }else{ alert("上傳失敗,有圖片未上傳完成"); //清空file this.emptyFile(); return false;//終止程序標識 } this.fileName=this._muuid(); return true;//繼續程序標識 }; /** * 自定義上傳結果 */ UploadPic.prototype.uploadResult = function (json) { this.isrun=0; alert("上傳完成"); }