前端上传图片压缩

<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>

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值