前端上傳多張圖片並壓縮
html:
<input type="file" id="choose" accept="image/*" multiple> //multiple屬性允許上傳多張
js:
$("#choose").change(function() { // 上傳事件觸發if (!this.files.length) return; // this.files獲取上傳圖片
var files = Array.prototype.slice.call(this.files); // 轉換為陣列
files.forEach(function(file, i) { // 圖片檔案迴圈
if (!/\/(?:jpeg|png|gif)/i.test(file.type)) return; // file.type獲取圖片格式
var reader = new FileReader(); // FileReader
var li = document.createElement("li");// 物件允許Web應用程式非同步讀取儲存在使用者計算機上的檔案(或原始資料緩衝區)的內容
var size = file.size / 1024 > 1024 ? (~~(10 * file.size / 1024 / 1024)) / 10 + "MB" : ~~(file.size / 1024) + "KB";//file.size圖片大小,~~轉換數字整形
li.innerHTML = '<div class="img"><img src=""/></div>';
var i;
i++;
$(".img-list").prepend($(li)); //圖片顯示頁面上
reader.onload = function() { //讀取操作成功
var result = this.result; //檔案內容,讀取操作完成後,此屬性才有效
var img = new Image(); //Image物件
img.src = result;
$(li).find('img').attr('src', result);
//如果圖片大小小於100kb,則直接上傳
if(result.length <= 100*1024) {//圖片小於100kb直接上傳
img = null;
// upload(result, file.type, $(li));
return;
}
if(img.complete) { //影象在瀏覽器載入完成
callback();
} else {
img.onload = callback; //當影象裝載完畢
}
function callback() {
var data = compress(img);//進行壓縮操作
upload(data, file.type, $(li));
img = null;
}
};
reader.readAsDataURL(file); //讀取file物件
})
});
function compress(img) {
var canvas = document.createElement("canvas"); //新建畫布
var ctx = canvas.getContext('2d'); //指定二維繪圖
var initSize = img.src.length;
var width = img.width;
var height = img.height;
var ratio;
if((ratio = width * height / 400000) > 1) { //圖片大小大於40w畫素則進行壓縮
ratio = Math.sqrt(ratio); //返回正平方根double值
width /= ratio;
height /= ratio;
} else {
ratio = 1;
}
canvas.width = width;
canvas.height = height;
ctx.fillStyle = "#fff"; //鋪底色
ctx.fillRect(0, 0, canvas.width, canvas.height); //繪製“被填充”矩形
//如果圖片畫素大於100萬則使用瓦片繪製
var count;
if((count = width * height / 100000) > 1) {
var tCanvas = document.createElement("canvas");
var tctx = tCanvas.getContext("2d");
count = ~~(Math.sqrt(count) + 1); //計算要分成多少塊瓦片
//計算每塊瓦片的寬和高
var nw = ~~(width / count);
var nh = ~~(height / count);
tCanvas.width = nw;
tCanvas.height = nh;
for(var i = 0; i < count; i++) {
for(var j = 0; j < count; j++) {
tctx.drawImage(img, i * nw * ratio, j * nh * ratio, nw * ratio, nh * ratio, 0, 0, nw, nh);
ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh);
}
}
} else {
ctx.drawImage(img, 0, 0, width, height);
}
//進行最小壓縮
var ndata = canvas.toDataURL('image/jpeg', 0.1); //返回包含圖片展示的 data URI 第二個引數標識圖片質量
tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0;
return ndata;
}