directTurnIntoBase64(fileObj, callback) { var r = new FileReader(); // 轉成base64 r.onload = function() { //變成字符串 imgBase64 = r.result; console.log(imgBase64); callback(imgBase64); } r.readAsDataURL(fileObj); //轉成Base64格式 }, compress(fileObj, callback) { var _this = this; if(typeof(FileReader) === 'undefined') { console.log("當前瀏覽器內核不支持base64圖標壓縮"); //調用上傳方式不壓縮 _this.directTurnIntoBase64(fileObj, callback); } else { try { var reader = new FileReader(); reader.onload = function(e) { var image = $('<img/>'); image.on('load', function() { var square = 700, //定義畫布的大小,也就是圖片壓縮以後的像素 canvas = document.createElement('canvas'), context = canvas.getContext('2d'), imageWidth = 0, //壓縮圖片的大小 imageHeight = 0, offsetX = 0, offsetY = 0, data = ''; canvas.width = square; canvas.height = square; context.clearRect(0, 0, square, square); if(this.width > this.height) { imageWidth = square; imageHeight = square; offsetX = -Math.round((imageWidth - square) / 2); } else { imageHeight = square; imageWidth = square; offsetY = -Math.round((imageHeight - square) / 2); } context.drawImage(this, offsetX, offsetY, imageWidth, imageHeight); var data = canvas.toDataURL('image/jpeg'); //壓縮完成執行回調 callback(data); }); image.attr('src', e.target.result); }; reader.readAsDataURL(fileObj); } catch(e) { console.log("壓縮失敗!"); //調用直接上傳方式 不壓縮 _this.directTurnIntoBase64(fileObj, callback); } } }, convertBase64UrlToBlob(urlData) { var bytes = window.atob(urlData.split(',')[1]); //去掉url的頭,並轉換爲byte //處理異常,將ascii碼小於0的轉換爲大於0 var ab = new ArrayBuffer(bytes.length); var ia = new Uint8Array(ab); for(var i = 0; i < bytes.length; i++) { ia[i] = bytes.charCodeAt(i); } return new Blob([ab], { type: 'image/png' }); },
以上就是主要代碼,接下來引用:vue
fileChanged(e) {
var _this = this; const item = e.target.files[0];
_this.compress(item, function(imgBase64) { // console.log(imgBase64) if(item.size > 524288) { item = _this.convertBase64UrlToBlob(imgBase64); } if(item.size > 2097152) { alert("圖片大小不能超過2M"); return; } _this.images =URL.createObjectURL(item); //壓縮的圖片進行回顯
_this.files = item;
});
},
注意壓縮後的圖片賦值只能在回調裏面進行賦值,若是寫到外面會失效。canvas
最後,圖片上傳給後臺要加入到formData裏面。瀏覽器
示例:app
formData.append("photo", this.files, "file_" + Date.parse(new Date()) + ".png"); //存入
console.log(formData.getAll('photo')); //打印檢查
這是使用js壓縮圖片,在哪都能用的,我是寫vue項目時使用過。但其實vue是有相關的壓縮圖片的依賴的,具體可查看:https://blog.csdn.net/qq_34794264/article/details/80278243this
很簡單,看看就能用了,更方便點url