話不多說,直接上代碼:
<input id="input-file" type="file" multiple="multiple" accept="image/*" >
$("#input-file").on("change",function(){
var filePath = $(this).val(), //獲取到input的value,裏面是文件的路徑
fileFormat = filePath.substring(filePath.lastIndexOf(".")).toLowerCase(),
imgBase64 = '', //存儲圖片的imgBase64
fileObj = document.getElementById('input-file').files[0]; //上傳文件的對象,要這樣寫才行,用jquery寫法獲取不到對象
// 檢查是否是圖片
if( !fileFormat.match(/.png|.jpg|.jpeg/) ) {
alert('上傳錯誤,文件格式必須爲:png/jpg/jpeg');
return;
}
// 調用函數,對圖片進行壓縮
compress(fileObj,function(imgBase64){
imgBase64 = imgBase64;//存儲轉換後的base64編碼
});
});
// 對圖片進行壓縮
function compress(fileObj, callback){
if ( typeof (FileReader) === 'undefined') {
console.log("當前瀏覽器內核不支持base64圖標壓縮");
//調用上傳方式不壓縮
directTurnIntoBase64(fileObj,callback);
} else {
var reader = new FileReader();
reader.onload = function (e) { //要先確保圖片完整獲取到,這是個異步事件
var image = new Image();
image.src=e.target.result;
image.onload = function(){
square = {$pic_compress}, //定義畫布的大小,也就是圖片壓縮之後的像素
canvas = document.createElement('canvas'), //創建canvas元素
context = canvas.getContext('2d'),
imageWidth = Math.round(square*image.width), //壓縮圖片的大小
imageHeight = Math.round(square*image.height),
data = '';
canvas.width = imageWidth;
canvas.height = imageHeight;
context.clearRect(0, 0, imageWidth, imageHeight); //在給定矩形內清空一個矩形
context.drawImage(this, 0, 0, imageWidth, imageHeight);
var data = canvas.toDataURL('image/jpeg',0.6);
//壓縮完成執行回調
callback(data);
};
};
reader.readAsDataURL(fileObj);
}
}
function directTurnIntoBase64(fileObj,callback){
var r = new FileReader();
// 轉成base64
r.onload = function(){
//變成字符串
imgBase64 = r.result;
//console.log(imgBase64);
callback(imgBase64);
}
r.readAsDataURL(fileObj); //轉成Base64格式
}