<van-uploader v-model="commentObj.imgModelList"
multiple
:max-size="5*1024*1024"
:max-count="9"
:before-read="beforeRead"
:after-read="afterRead"
:before-delete="beforeDelete"
@oversize="picOversize" />
async afterRead (file) {
if (file.length) {
file.map(async (item, i) => {
item.status = 'uploading'
let base64Item = await this.compressImg (item.file)
if (i === file.length - 1) {
file.map(item => {
item.status = 'done'
})
}
})
} else {
let base64Item2 = await this.compressImg (file.file)
file.status = 'uploading'
file.status = 'done'
}
},
compressImg (file) {
let self = this
if (!file || !window.FileReader) return
if (/^image/.test(file.type)) {
let reader = new FileReader()
reader.readAsDataURL(file)
return new Promise((resolve, reject) => {
reader.onloadend = function () {
let img = new Image()
img.src = this.result
if (this.result.length <= 500 * 1024) {
resolve(this.result)
} else {
img.onload = function () {
let canvas = document.createElement('canvas')
let ctx = canvas.getContext('2d')
let tCanvas = document.createElement('canvas')
let tctx = tCanvas.getContext('2d')
let width = img.width
let height = img.height
let ratio
if ((ratio = (width * height) / 4000000) > 1) {
console.log('大于400万像素')
ratio = Math.sqrt(ratio)
width /= ratio
height /= ratio
} else {
ratio = 1
}
canvas.width = width
canvas.height = height
ctx.fillStyle = '#fff'
ctx.fillRect(0, 0, canvas.width, canvas.height)
let count
if ((count = (width * height) / 1000000) > 1) {
count = ~~(Math.sqrt(count) + 1)
let nw = ~~(width / count)
let nh = ~~(height / count)
tCanvas.width = nw
tCanvas.height = nh
for (let i = 0; i < count; i++) {
for (let j = 0; j < count; j++) {
tctx.drawImage(img, i * nw * ratio, j * nh * ratio, nw * ratio, nh * ratio, 0, 0, nw, nh)
ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh)
}
}
} else {
ctx.drawImage(img, 0, 0, width, height)
}
let quailty = 0.5
let newBase64 = canvas.toDataURL('image/jpeg', quailty)
tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0
resolve(newBase64)
}
}
}
})
}
}