1.html中添加隐藏的input
<img
class="input-img-wrap"
v-on:click="imgClick()"
:src="fapiao"
v-if="fapiao"
/>
<div class="input-img-wrap" @click="imgClick" v-else>
<img src="../../assets/img/common/+_icon.png" alt="" />
<span>上传图片</span>
</div>
<input
style="display: none;"
type="file"
id="uploadFile"
accept="image/png,image/jpeg"
v-on:change="readLocalFile()"
/>
2.压缩图片
核心代码:
1.FileReader将input中的图片本地url变为图片Base64编码。
var localFile = document.getElementById(“uploadFile”).files[0];
var reader = new FileReader();
reader.onerror
reader.readAsDataURL(localFile , ‘UTF-8’)
reader.onLoad(function(event) {
content = event.target.result;
})
2.通过Image赋值src,计算图片宽高创建同样宽高的canvas,然后将Image绘制到canvas上,通过canvas.toDataURL(“image/jpg”, rate)获得压缩的图片Base64数据
data() {
return {
fapiao: ""
};
},
mounted() {
vm = this;
},
methods: {
imgClick: function() {
document.getElementById("uploadFile").click();
},
//点击选中图片
async readLocalFile() {
var localFile = document.getElementById("uploadFile").files[0];
var reader = new FileReader();
var content;
var compress = this.compress;
reader.onload = function(event) {
content = event.target.result;
compress(content, 450, function(content0) {
console.log("final=" + content0.length / 1024 + "KB");
vm.fapiao = content0;
});
};
reader.onerror = function() {
alert("error");
};
reader.readAsDataURL(localFile, "UTF-8");
},
// 压缩图片
compress: function(content, size, callback) {
if (content.length <= size * 1024) {
callback(content);
return;
}
let canvas = document.createElement("canvas");
let ctx = canvas.getContext("2d");
let img = new Image();
img.src = content;
img.onload = function() {
let width = img.width;
let height = img.height;
canvas.width = width;
canvas.height = height;
// 铺底色
ctx.fillStyle = "#fff";
ctx.fillRect(0, 0, width, height);
ctx.drawImage(img, 0, 0, width, height);
let rate = (1024 * size) / content.length;
console.log("size=" + size + " rate=" + rate);
console.log("**压缩前**" + content.length / 1024 + "KB");
//进行压缩
content = canvas.toDataURL("image/jpeg", rate);
console.log("**压缩后**" + content.length / 1024 + "KB");
callback(content);
};
}
}