// src转base64(1)
getBase64(img) {
function getBase64Image(img, width, height) {
var canvas = document.createElement('canvas')
canvas.width = width ? width : img.width
canvas.height = height ? height : img.height
var ctx = canvas.getContext('2d')
ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
var dataURL = canvas.toDataURL()
return dataURL
}
var image = new Image()
image.setAttribute('crossOrigin', 'anonymous') // 解决跨域
image.setAttribute('referrerpolicy', 'no-referrer') // 不用带 referer 所有的防止外链的行为都会失效
image.crossOrigin = '*'
image.src = img + '?v=' + Math.random() // 解决图片URL缓存问题
return new Promise((resolve, reject) => {
console.log(reject)
image.onload = function () {
resolve(getBase64Image(image)) //将base64传给done上传处理
}
})
},
// src转换成base64(2)
getBase64(img_url) {
function toBase64(image) {
const canvas = document.createElement('canvas')
canvas.width = image.width
canvas.height = image.height
const ctx = canvas.getContext('2d')
ctx.drawImage(image, 0, 0, image.width, image.height)
const base64 = canvas.toDataURL('image/png')
return base64
}
return new Promise((resolve, reject) => {
console.log(reject)
const image = new Image()
image.setAttribute('crossOrigin', 'anonymous') // 解决跨域
image.setAttribute('referrerpolicy', 'no-referrer') // 不用带 referer 所有的防止外链的行为都会失效
image.crossOrigin = '*'
image.src = img_url + '?v=' + Math.random() // 解决图片URL缓存问题
image.onload = () => {
resolve(toBase64(image))
}
})
},
// src转换成Blob
getImgBlob(imgUrl) {
return new Promise((resolve, reject) => {
const img = new Image()
img.setAttribute('crossorigin', 'anonymous') // 允许图片跨域
img.setAttribute('referrerpolicy', 'no-referrer') // 不用带 referer 所有的防止外链的行为都会失效
img.onload = () => {
const canvas = document.createElement('canvas')
canvas.height = img.height
canvas.width = img.width
const ctx = canvas.getContext('2d')
ctx.drawImage(img, 0, 0, img.width, img.height)
canvas.toBlob((b) => resolve(b))
}
img.onerror = (err) => reject(err)
img.src = imgUrl
})
},
// base64转换为file文件流
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)
}
return new File([u8arr], `${filename}.${suffix}`, {
type: mime,
})
},
//使用
// 图片转成Blob格式
// that.getImgBlob(imageArr[i]).then((url) => {
// console.log(
// new window.File([url], Math.random(), {
// type: url.type,
// })
// )
// Blob格式转成file文件
// formData.append(
// 'files',
// new window.File([url], Math.random(), {
// type: url.type,
// })
// )
// })