1 // 文件上傳成功 2 function compress(){ 3 var file = document.getElementById('file_cw').files[0]; 4 // 壓縮圖片需要的一些元素和對象 5 var reader = new FileReader(), 6 //創建一個img對象 7 img = new Image(); 8 reader.readAsDataURL(file); 9 // 文件base64化,以便獲知圖片原始尺寸 10 reader.onload = function(e) { 11 img.src = e.target.result; 12 }; 13 14 15 // base64地址圖片加載完畢后執行 16 img.onload = function () { 17 // 縮放圖片需要的canvas(也可以在DOM中直接定義canvas標簽,這樣就能把壓縮完的圖片不轉base64也能直接顯示出來) 18 var canvas = document.createElement('canvas'); 19 var context = canvas.getContext('2d'); 20 21 // 圖片原始尺寸 22 var originWidth = this.width; 23 var originHeight = this.height; 24 25 // 最大尺寸限制,可通過設置寬高來實現圖片壓縮程度 26 var maxWidth = 1200, 27 maxHeight = 1200; 28 // 目標尺寸 29 var targetWidth = originWidth, 30 targetHeight = originHeight; 31 // 圖片尺寸超過300x300的限制 32 if(originWidth > maxWidth || originHeight > maxHeight) { 33 if(originWidth / originHeight > maxWidth / maxHeight) { 34 // 更寬,按照寬度限定尺寸 35 targetWidth = maxWidth; 36 targetHeight = Math.round(maxWidth * (originHeight / originWidth)); 37 } else { 38 targetHeight = maxHeight; 39 targetWidth = Math.round(maxHeight * (originWidth / originHeight)); 40 } 41 } 42 // canvas對圖片進行縮放 43 canvas.width = targetWidth; 44 canvas.height = targetHeight; 45 // 清除畫布 46 context.clearRect(0, 0, targetWidth, targetHeight); 47 // 圖片壓縮 48 context.drawImage(img, 0, 0, targetWidth, targetHeight); 49 /*第一個參數是創建的img對象;第二三個參數是左上角坐標,后面兩個是畫布區域寬高*/ 50 51 //壓縮后的圖片轉base64 url 52 /*canvas.toDataURL(mimeType, qualityArgument),mimeType 默認值是'image/png'; 53 * qualityArgument表示導出的圖片質量,只有導出為jpeg和webp格式的時候此參數才有效,默認值是0.92*/ 54 var newUrl = canvas.toDataURL('image/jpeg', 0.92);//base64 格式 55 //downLoad(newUrl,file["name"]);// 測試下載圖片質量 56 57 //調用 base64 轉 file文件 58 var blob = dataURLtoBlob(newUrl);
var aasfile = blobToFile(blob, file["name"]);
var aafile = new File([aasfile], file["name"], { type: file["type"] });
60 61 formData.append('file', aafile); 62 return 63 $.ajax({ 64 url: "./upload.do", 65 type: "post", 66 data: formData, 67 async: false, 68 contentType: false, 69 processData: false, 70 dataType: "json", 71 mimeType: "multipart/form-data", 72 success: function (data) { 73 console.log(data); 74 js.showMessage("上傳成功!"); 75 } 76 }); 77 78 }; 79 } 80 // 測試下載圖片質量 81 function downLoad(content,fileName){ 82 var aEle = document.createElement("a");// 創建a標簽 83 aEle.download = fileName;// 設置下載文件的文件名 84 aEle.href = content; 85 aEle.click();// 設置點擊事件 86 87 } 88 //將base64轉換為blob 89 function dataURLtoBlob(dataurl) { 90 var arr = dataurl.split(','), 91 mime = arr[0].match(/:(.*?);/)[1], 92 bstr = atob(arr[1]), 93 n = bstr.length, 94 u8arr = new Uint8Array(n); 95 while (n--) { 96 u8arr[n] = bstr.charCodeAt(n); 97 } 98 return new Blob([u8arr], { type: mime }); 99 }; 100 //將blob轉換為file 101 function blobToFile(theBlob, fileName){ 102 theBlob.lastModifiedDate = new Date(); 103 theBlob.name = fileName; 104 return theBlob; 105 };