js實現對上傳圖片進行壓縮並且預覽
阿新 • • 發佈:2019-02-07
js實現對上傳圖片的路徑轉成base64編碼,並且對圖片進行壓縮,實現預覽功能
需要先引入jquery: <script src="http://i.gtimg.cn/qzone/biz/gdt/lib/jquery/jquery-2.1.4.js?max_age=31536000"></script>
1、html如下
<body> <input type="file" id="upLoad" name="image" > <!-- 顯示上傳之後的圖片 --> <div id='previewImg'> <img src="" id='viewImg'/> </div> </body>
2、css如下
#previewImg{ background-color: black; width: 400px; height:400px; display: table-cell; vertical-align: middle; text-align: center; } #previewImg img{ max-height: 100%; max-width: 100%; } #upLoad{ margin-bottom: 20px; }
3、js如下
$(function(){ $('#upLoad').on('change',function(){ var filePath = $(this).val(), //獲取到input的value,裡面是檔案的路徑 fileFormat = filePath.substring(filePath.lastIndexOf(".")).toLowerCase(), imgBase64 = '', //儲存圖片的imgBase64 fileObj = document.getElementById('upLoad').files[0]; //上傳檔案的物件,要這樣寫才行,用jquery寫法獲取不到物件 // 檢查是否是圖片 if( !fileFormat.match(/.png|.jpg|.jpeg/) ) { alert('上傳錯誤,檔案格式必須為:png/jpg/jpeg'); return; } // 呼叫函式,對圖片進行壓縮 compress(fileObj,function(imgBase64){ imgBase64 = imgBase64; //儲存轉換的base64編碼 $('#viewImg').attr('src',imgBase64); //顯示預覽圖片 }); }); // 不對圖片進行壓縮,直接轉成base64 function directTurnIntoBase64(fileObj,callback){ var r = new FileReader(); // 轉成base64 r.onload = function(){ //變成字串 imgBase64 = r.result; console.log(imgBase64); callback(imgBase64); } r.readAsDataURL(fileObj); //轉成Base64格式 } // 對圖片進行壓縮 function compress(fileObj, callback) { if ( typeof (FileReader) === 'undefined') { console.log("當前瀏覽器核心不支援base64圖示壓縮"); //呼叫上傳方式不壓縮 directTurnIntoBase64(fileObj,callback); } else { try { var reader = new FileReader(); reader.onload = function (e) { var image = $('<img/>'); image.load(function(){ 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 = Math.round(square * this.width / this.height); imageHeight = square; offsetX = - Math.round((imageWidth - square) / 2); } else { imageHeight = Math.round(square * this.height / this.width); 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("壓縮失敗!"); //呼叫直接上傳方式 不壓縮 directTurnIntoBase64(fileObj,callback); } } } });
4、顯示效果如下:
未上傳前的效果圖
上傳之後的效果圖
5、通過上面的設定,可以通過js對本地上傳的圖片的地址進行base64編碼,並在本地預覽
6、問題:可以發現上傳圖片之後,父級的高度比原來多了3px,如上圖所示,多出來的黑色部分,就是在加上圖片的src之後被擠出來多的高 度
7、原因:img是類似text的元素,在結束的時候會在末尾加上一個空白符,所以多出3pxde 黑色部分
8、解決方法:給img元素加上樣式:display:block就可以了
9、修改後的img的css:
#previewImg img{
max-height: 100%;
max-width: 100%;
display:block;
}
10、顯示效果:多餘的黑色部分被去掉了