img转Base64
function imgToBase64(imgFile, maxLen) {
return new Promise((resolve, reject) => {
const img = new Image()
const reader = new FileReader()
reader.onload = function() {
const url = reader.result
img.src = url
}
img.onload = function() {
const width = img.width
const height = img.height
let rate = 1
if (width >= height) {
if (width > maxLen) {
rate = maxLen / width
}
} else {
if (height > maxLen) {
rate = maxLen / height
}
}
img.width = width * rate
img.height = height * rate
const canvas = document.createElement('canvas')
const ctx = canvas.getContext('2d')
canvas.width = img.width
canvas.height = img.height
ctx.drawImage(img, 0, 0, img.width, img.height)
const base64 = canvas.toDataURL('image/jpeg', 0.9)
resolve(base64)
}
reader.readAsDataURL(imgFile)
})
}