最近遇到需要将img标签里面src是网络图片转base64,这里记录一下。
function getBase64Image(src) {
return new Promise(resolve => {
let xhr = new XMLHttpRequest()
xhr.open('get', src, true)
xhr.responseType = 'blob'
xhr.onload = function () {
if (this.status == 200) {
let blob = this.response
let oFileReader = new FileReader()
oFileReader.onloadend = function (e) {
const base64 = e.target.result
resolve(base64)
}
oFileReader.readAsDataURL(blob)
}
}
xhr.send()
})
}