<template>
<div class="img-upload">
<img class="img" ref="img" :src="imgSrc" alt="">
<input ref="file" type="file" :accept=accept @change="imgSelect($event.target)">
<canvas ref="canvas"></canvas>
<img class="img" :src="base64" alt="">
<button type="button" @click="selectImg">
<slot></slot>
</button>
</div>
</template>
<script>
export default {
name: "ImgUpload",
props: {
accept: {
default: 'image/*'
},
maxSize: {
default: 204800 //200KB
},
suffix: {
default: '.jpeg'
}
},
data(){
return {
imgSrc: '',
base64: '',
}
},
methods: {
imgSelect(el){
let file = el.files[0];
if(file){
let reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => {
this.imgSrc = reader.result;
this.$nextTick(() => {
let size = file.size;
console.log("原始大小:" + size);
if(size > this.maxSize){
this.toBase64(size);
}else{
this.$emit('update:uploadBase64', this.imgSrc)
this.$emit('callback');
}
})
}
}else{
this.imgSrc = '';
this.base64 = '';
}
el.value = ""
},
selectImg(){
this.$refs.file.click();
},
toBase64(size){
console.log("压缩前:" + size);
let canvas = this.$refs.canvas;
let img = this.$refs.img;
let ctx = canvas.getContext('2d');
img.onload = () => {
console.log(img.naturalWidth);
console.log(img.naturalHeight);
let width = img.naturalWidth;
let height = img.naturalHeight;
let ratio = width / height;
let pixelPerSize = width * height / size;
let shrinkHeight = Math.sqrt(this.maxSize * pixelPerSize / ratio);
let shrinkWidth = shrinkHeight * ratio;
canvas.width = shrinkWidth;
canvas.height = shrinkHeight;
console.log(canvas.width);
console.log(canvas.height);
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
let imgSrc = canvas.toDataURL('image/' + this.suffix, 1);
let newSize = this.calcBase64Size(imgSrc);
if(newSize > this.maxSize){
img.src = imgSrc;
return this.toBase64(newSize);
}else{
this.base64 = imgSrc;
this.$emit('update:uploadBase64', this.base64)
this.$emit('callback');
}
}
},
calcBase64Size(base64){
let tag="base64,";
let baseStr = base64.substring(base64.indexOf(tag) + tag.length);
//console.log(baseStr);
let eqTagIndex=baseStr.indexOf("=");
baseStr = eqTagIndex != -1 ? baseStr.substring(0, eqTagIndex) : baseStr;
let baseStrLength = baseStr.length;
return baseStrLength - (baseStrLength / 8) * 2;
}
}
}
</script>