将url地址转换成file对象
const getFileFromUrl = (url: any, fileName: any) => {
return new Promise((resolve, reject) => {
var blob = null
var xhr = new XMLHttpRequest()
xhr.open('GET', url)
//此处类型依据具体情况设置
xhr.setRequestHeader('Accept', 'image/jpeg')
xhr.responseType = 'blob'//先将文件转成blob
// 加载时处理
xhr.onload = () => {
// 获取返回结果
blob = xhr.response
//此处类型依据具体情况设置,同上
let file = new File([blob], fileName, { type: 'image/jpeg' })
// 返回结果
resolve(file)
}
xhr.onerror = (e) => {
reject(e)
}
// 发送
xhr.send()
})
}
getFileFromUrl(Url, 'miniCode.jpg').then((res) => {//miniCode.jpg为文件名字
file = res
})
先将文件利用ajax请求转成blob类型,然后再将其变成file对象
file转url地址
image.src = URL.createObjectURL(file) //file为file文件
将canvas转成图片
const img = (file: any) => {
//file为file文件
return new Promise((resolve, reject) => {
const reader = new FileReader()
reader.onload = function (event) {
const dataURL = event.target.result
const image = new Image()
image.src = URL.createObjectURL(file)//将file文件转成url地址
image.onload = async () => {//必须在图片加载后进行
const canvas = document.createElement('canvas')
const context = canvas.getContext('2d')
canvas.width = 635
canvas.height = 850
context.drawImage(image, 0, 0, 635, 850)
resolve(dataURLtoFile(canvas.toDataURL('image/png'), 'image.png'))
}
}
reader.readAsDataURL(file)
})
}
const dataURLtoFile = (dataURL, filename) => {
const arr = dataURL.split(',')
const mime = arr[0].match(/:(.*?);/)[1]
const bstr = atob(arr[1])
let n = bstr.length
const u8arr = new Uint8Array(n)
while (n--) {
u8arr[n] = bstr.charCodeAt(n)
}
return new File([u8arr], filename, { type: mime })
}