第一种:Blob和FileReader 对象
实现原理:
使用xhr请求图片,并设置返回的文件类型为Blob对象[xhr.responseType = “blob”]
使用FileReader 对象接收blob
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() })
第二种:canvas.toDataURL()
实现原理:
使用canvas.toDataURL()方法
需要解决图片跨域问题 image.crossOrigin = ‘’;
return new Promise(resolve => { const img = new Image() img.crossOrigin = '' img.src = src img.onload = function () { const canvas = document.createElement('canvas') canvas.width = img.width canvas.height = img.height const ctx = canvas.getContext('2d') ctx?.drawImage(img, 0, 0, img.width, img.height) const ext = img.src.substring(img.src.lastIndexOf('.') + 1).toLowerCase() const dataURL = canvas.toDataURL('image/' + ext) resolve(dataURL) }
附:需要转化的图片很可能存在跨域问题,要么后端处理,要么前端处理。这里是使用时在vue中处理了跨域问题
devServer: { port: port, open: true, overlay: { warnings: false, errors: true }, proxy: { '/api': { target: 'http://-----:8084' changeOrigin: true, ws: true, pathRewrite: { '^/api': '' } } } },