前端JS轉圖片爲base64並壓縮

addImg(event) {
var imgFile=event.target.files[0];
//判斷類型是否是圖片
if(!/image\/\w+/.test(imgFile.type)){
alert("請確保文件爲圖像類型");
return ;
}
//經過html5 特性fileReader轉換base64  經過compressImg方法進行壓縮
var reader =new FileReader();
reader.readAsDataURL(imgFile);
const that = this;
reader.onloadend=function(){ //文件讀取結束的時候上傳到服務器
that.results = reader.result;
that.$vux.loading.show({
text: '上傳中'
})
var img = document.querySelector("#img");
img.src = reader.result;
var width = img.width;
var height = img.height;
var result = compressImg(img,width,height);
 
that.$emit('sendImgInfo',result); //將上傳的圖片以base64形式傳給父組件
}
}
 
 
/**
* 圖片壓縮
*/
export const compressImg = (img, width, height) => {
if(img.src.length <2000000) { //小於200K的壓縮
return img.src;
}
//用於壓縮圖片的canvas
console.log(width + "," + height)
let canvas = document.createElement("canvas");
let ctx = canvas.getContext('2d');

// 瓦片canvas
// var tCanvas = document.createElement("canvas");
// var tctx = tCanvas.getContext("2d");

let initSize = img.src.length;
// console.log(img.src)

var ratio;
if ((ratio = width * height / 4000000) > 1) {
ratio *=10;

width /= ratio;
height /= ratio;
} else {
ratio = 5;
}
console.log('ratio=' +ratio)
canvas.width = width * 2;
console.log(width)
canvas.height = height * 2;
//鋪底色
ctx.fillStyle = "#fff";
ctx.fillRect(0, 0, canvas.width, canvas.height);
//若是圖片像素大於100萬則使用瓦片繪製
// var count;
// if ((count = width * height / 1000000) > 1) {
// console.log('count='+count)
// 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 * 2, nh * ratio * 2, 0, 0, nw, nh);
// ctx.drawImage(tCanvas, i * nw, j * nh, nw * 2, nh * 2);
// }
// }
// } else {
ctx.drawImage(img, 0, 0, width * 2, height * 2);
// }
//進行最小壓縮
let dataURL = canvas.toDataURL('image/jpeg', 1);

console.log('壓縮前:' + initSize);
console.log('壓縮後:' + dataURL.length);
console.log('壓縮率:' + ~~(100 * (initSize - dataURL.length) / initSize) + "%");
console.log(dataURL)
return dataURL;
}
相關文章
相關標籤/搜索