参考文章:
https://blog.csdn.net/rmnctn/article/details/79452709
https://www.cnblogs.com/apanly/p/5731086.html
<div>
<div class="image-list">
<input type="file" accept="image/jpg,image/png,image/jpeg,image/gif" ref="input" capture="camera"
@change="onFileChange"
style="display: none;">
<button v-show="isPhoto" @click="addPic" class="add-img"/>
<ul class="list-ul" v-show="!isPhoto">
<li class="list-li " v-for="(iu, index) in imgUrls">
<a class="list-link" @click='previewImage(iu)'>
<img :src="iu">
</a>
<span class="list-img-close" @click='delImage(index)'></span>
</li>
<li class="list-li">
<span class="add-img" @click.stop="addPic"> </span>
</li>
</ul>
</div>
<div class="add-preview" v-show="isPreview" @click="closePreview">
<img :src="previewImg">
</div>
<div style="font: 0px/0px sans-serif;clear: both;display: block"></div>
</div>
addPic: function (e) {
this.$refs.input.click()
//ios 下不晓得为何还要再执行一次
if (this.$isIos) {
this.$refs.input.click()
}
return false
},
onFileChange: function (e) {
var that = this
var files = e.target.files || e.dataTransfer.files
if (!files.length) return
var reader = new FileReader()
reader.onload = function (e) {
//base64 图片信息
// alert(this.result);
// 自已处理
that.compress(this.result)
}
reader.readAsDataURL(files[0])
//使用 lrz 进行图片压缩处理
// this.createImage(files, e)
},
compress: function (res) {
var that = this
var img = new Image(),
maxH = 300
img.onload = function () {
var cvs = document.createElement('canvas'),
ctx = cvs.getContext('2d')
if (img.height > maxH) {
img.width *= maxH / img.height
img.height = maxH
}
cvs.width = img.width
cvs.height = img.height
ctx.clearRect(0, 0, cvs.width, cvs.height)
ctx.drawImage(img, 0, 0, img.width, img.height)
var dataUrl = cvs.toDataURL('image/jpeg', 1)
that.imgUrls.push(dataUrl)
// 上传略
that.upload(dataUrl)
}
img.src = res
},
upload: function (image_data) {
/*这里写上次方法,图片流是base64_encode的*/
},
createImage: function (file, e) {
let vm = this
lrz(file[0], {
width: 680,
}).then(function (rst) {
vm.imgUrls.push(rst.base64)
return rst
}).always(function () {
// 清空文件上传控件的值
e.target.value = null
})
},