<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<input type="file" onchange="change(this)">
<div id="imgBox">
</div>
</body>
<script>
function change(self){
/*
* 以下注釋爲上傳圖片
* */
// let inputDOM = this.$refs.inputer;
// let param = new FormData(); //創建form對象
// for(let key in inputDOM.files){
// param.append('file',files[key]);//通過append向form對象添加數據
// }
// console.log(param.get('file')); //FormData私有類對象,訪問不到,可以通過get判斷值是否傳進去
// let config = {
// headers:{'Content-Type':'multipart/form-data'}
// }; //添加請求頭
// axios.post('http://localhost:8099/upload/image',param,config)
// .then(response=>{
// console.log(response.data);
// })
/*
* 以下爲上傳圖片壓縮,轉base64並添加水印
* */
console.log(self.files);
//創建一個讀取文件的對象
let reader = new FileReader();
//讀取文件,轉碼
reader.readAsDataURL(self.files[0]);
reader.onload = function (e) {
let base64 = e.target.result; //轉碼過後的base64編碼
console.log("壓縮前", base64.length / 1024);
//創建一個圖片
let newImage = new Image();
let quality = 0.6; //壓縮係數0-1之間,壓縮到0.9以上會有bug,注意!(可以自行設置)
newImage.src = base64;
newImage.setAttribute("crossOrigin", 'Anonymous'); //url爲外域時需要
let imgWidth, imgHeight;
newImage.onload = function () {
imgWidth = this.width;
imgHeight = this.height;
//給生成圖片設置一個默認的最大寬/高(可以自行設置)
let myWidth = 800;
//準備在畫布上繪製圖片
let canvas = document.createElement("canvas");
let ctx = canvas.getContext("2d");
//判斷上傳的圖片的寬高是否超過設置的默認最大值,以及設置同比例的寬高
if (Math.max(imgWidth, imgHeight) > myWidth) {
if (imgWidth > imgHeight) {
canvas.width = myWidth;
canvas.height = myWidth * imgHeight / imgWidth;
} else {
canvas.height = myWidth;
canvas.width = myWidth * imgWidth / imgHeight;
}
} else {
canvas.width = imgWidth;
canvas.height = imgHeight;
}
//清空畫布
ctx.clearRect(0, 0, canvas.width, canvas.height);
//開始繪製圖片到畫布上
ctx.drawImage(this, 0, 0, canvas.width, canvas.height);
//繪製水印
//ctx.font="20px microsoft yahei";
//ctx.fillStyle="rgba(255,255,255,0.5)";
//ctx.fillText('水印文字',100,100)
let newBase64 = canvas.toDataURL("image/jpeg", quality);//壓縮圖片大小(關鍵代碼)
// 獲取到當前的圖片的大小,然後調整成自己需要的大小,例如說需要200KB-500KB之間(可以自行設置)
while (newBase64.length / 1024 > 500) {
quality -= 0.02;
newBase64 = canvas.toDataURL("image/jpeg", quality);
}
while (newBase64.length / 1024 < 200 && base64.length / 1024 > 200) {
quality += 0.02;
newBase64 = canvas.toDataURL("image/jpeg", quality);
}
myCallback(newBase64);//回調函數,做你想要的操作(可以自行設置)
}
};
}
function myCallback(base64) {
console.log("壓縮後", base64.length / 1024)
document.getElementById("imgBox").innerHTML="<img src="+base64+">"
}
</script>
</html>