imageUrlToBase64(imageUrl) {
let image = new Image() // 一定要设置为let,不然图片不显示
image.setAttribute('crossOrigin', 'anonymous') // 解决跨域问题
image.src = imageUrl +"&v=" + Math.random()
image.onload = () => {
var canvas = document.createElement("canvas")
canvas.width = image.width
canvas.height = image.height
var context = canvas.getContext('2d')
context.drawImage(image, 0, 0, image.width, image.height)
var quality = 0.8
var dataURL = canvas.toDataURL("image/jpeg", quality) // 使用toDataUrl将图片转换成jpeg的格式,不要把图片压缩成png,因为压缩成png后base64的字符串可能比不转换前的长!
this.base64toFile(dataURL)
Base64转换为二进制文件流(binary)
base64toFile (dataurl, filename = 'file') {
let arr = dataurl.split(',')
let mime = arr[0].match(/:(.*?);/)[1]
let suffix = mime.split('/')[1]
let bstr = atob(arr[1])
let n = bstr.length
let u8arr = new Uint8Array(n)
while (n--) {
u8arr[n] = bstr.charCodeAt(n)
let file = new File([u8arr], `${filename}.${suffix}`, {
type: mime
console.log(file)