图片压缩预览上传
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script>
// rem
(function (doc, win) {
var docEl = doc.documentElement, resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
recalc = function () {
var clientWidth = docEl.clientWidth;
if (!clientWidth) return;
if (clientWidth >= 750) {
docEl.style.fontSize = '100px';
}
else {
docEl.style.fontSize = 100 * (clientWidth / 750) + 'px';
}
};
if (!doc.addEventListener) return;
win.addEventListener(resizeEvt, recalc, false);
doc.addEventListener('DOMContentLoaded', recalc, false);
})(document, window);
</script>
<script src="https://cdn.bootcss.com/vue/2.6.10/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<title>图片上传预览压缩</title>
<style>
* {
margin: 0;
padding: 0;
}
ul, li {
list-style: none;
}
@font-face {
font-family: 'iconfont'; /* project id 1209692 */
src: url('//at.alicdn.com/t/font_1209692_3jqapk24q4n.eot');
src: url('//at.alicdn.com/t/font_1209692_3jqapk24q4n.eot?#iefix') format('embedded-opentype'),
url('//at.alicdn.com/t/font_1209692_3jqapk24q4n.woff2') format('woff2'),
url('//at.alicdn.com/t/font_1209692_3jqapk24q4n.woff') format('woff'),
url('//at.alicdn.com/t/font_1209692_3jqapk24q4n.ttf') format('truetype'),
url('//at.alicdn.com/t/font_1209692_3jqapk24q4n.svg#iconfont') format('svg');
}
.iconfont {
font-family: "iconfont" !important;
font-size: 16px;
font-style: normal;
-webkit-font-smoothing: antialiased;
-webkit-text-stroke-width: 0.2px;
-moz-osx-font-smoothing: grayscale;
}
.clearfix:after {
content: "";
display: block;
height: 0;
clear: both;
visibility: hidden;
overflow: hidden;
}
.clearfix {
*zoom: 1;
}
.load {
position: relative;
top: 0;
left: 0;
width: 2rem;
height: 2rem;
text-align: center;
line-height: 2rem;
border-radius: .1rem;
border: 1px dashed #cccccc;
color: #cccccc;
font-size: .2rem;
}
input {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
opacity: 0;
}
ul {
margin: 0 auto;
}
ul > li {
float: left;
width: 2rem;
height: 2rem;
overflow: hidden;
border-radius: .2rem;
position: relative;
margin: .1rem;
}
li > img {
height: 2rem;
width: 2rem;
}
li > i {
display: block;
position: absolute;
top: 0;
right: 0;
width: .4rem;
height: .4rem;
line-height: .4rem;
background: rgba(0, 0, 0, 0.4);
color: #FFFFFF;
font-size: .4rem;
}
.btn {
margin: .2rem auto;
border-radius: .1rem;
width: 5.2rem;
height: .68rem;
line-height: .68rem;
background: #fc6c00;
color: #FFFFFF;
font-size: .3rem;
text-align: center;
}
</style>
</head>
<body>
<div id="app">
<ul class="clearfix">
<li v-for="(p,index) in imgArr">
<img class="item" :src=p alt="">
<i @click="delImg(index)" class="iconfont"></i>
</li>
<li class="load">
上传图片
<input type="file" name="" id="form" @change="uploadIMG">
</li>
</ul>
<div class="btn" @click="uploadImg()">
上传
</div>
</div>
<script>
var vm = new Vue({
el: '#app',
data() {
return {
imgArr: []
}
},
methods: {
uploadIMG: function (e) {
// 读取图片信息
// let files = e.files[0] // pc端用法
let files = e.target.files || e.dataTransfer.files;
if (!files.length) return;
let picture = files[0];
// console.log(files.length,picture, picture.size / 1024);
if (picture.size / 1024 > 5000) {
alert("图片太大 无法上传");
} else {
this.imgPreview(picture);
}
},
imgPreview: function (file, callback) {
let that = this;
//判断支不支持FileReader
if (!file || !window.FileReader) return;
if (/^image/.test(file.type)) {
//创建一个reader
let reader = new FileReader();
//将图片转成base64格式
reader.readAsDataURL(file);
//读取成功后的回调
reader.onloadend = function () {
let result = this.result;
let img = new Image();
img.src = result;
// console.log("*未压缩前的图片大小*",result.length);
img.onload = function () {
let data = that.compress(img);
that.imgArr.push(data);
// base64转成bolb
// let blob = that.dataURItoBlob(data);
// console.log("**base64转blob对象*",blob);
// var formData = new FormData();
// formData.append("file", blob);
// console.log("*将blob对象转成formData对象*",formData.get("file"));
};
console.log(that.imgArr)
};
}
},
// 压缩图片
compress: function (img) {
let canvas = document.createElement("canvas");
let ctx = canvas.getContext("2d");
let initSize = img.src.length;
let width = img.width;
let height = img.height;
canvas.width = width;
canvas.height = height;
// 铺底色
ctx.fillStyle = "#fff";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0, 0, width, height);
//进行压缩
let ndata = canvas.toDataURL("image/jpeg", 0.2);
//console.log("*******压缩后的图片大小*******",ndata);
return ndata;
},
// base64转成bolb对象
dataURItoBlob:function(base64Data) {
var byteString;
if (base64Data.split(",")[0].indexOf("base64") >= 0)
byteString = atob(base64Data.split(",")[1]);
else byteString = unescape(base64Data.split(",")[1]);
var mimeString = base64Data
.split(",")[0]
.split(":")[1]
.split(";")[0];
var ia = new Uint8Array(byteString.length);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ia], {type: mimeString});
},
delImg(n) {
console.log(n)
this.imgArr.splice(n, 1);
},
uploadImg() {
// 上传图片
if(this.imgArr.length<=0){
alert("请添加图片");
return
}
axios.get('/接口地址', {
params: {
imgArr: this.imgArr
}
}).then(success=> {
console.log("请求成功",success);
}).catch(error=> {
console.log("请求失败",error);
});
}
}
})
</script>
</body>
</html>
欢迎纠错 ~
网友评论