两种方式:
1. 利用canvas绘制图片:适用转换本地路径图片
2. 通过网络请求图片地址,并返回blob格式,再操作:适用服务器端图片
1.利用canvas绘制
data() {
return {
img4:""
}
},
mounted(){
this.imgToBase64Cancas('./assets/image/1.jpg',(base64)=>{
this.img4 = base64
})
},
methods:{
imgToBase64Cancas(url,callback){
const image = new Image()
image.src = url
image.onload = () => {
const canvas = document.createElement('canvas')
canvas.width = image.naturalWidth // 使用 naturalWidth 为了保证图片的清晰度
canvas.height = image.naturalHeight
canvas.style.width = `${canvas.width / window.devicePixelRatio}px`
canvas.style.height = `${canvas.height / window.devicePixelRatio}px`
const ctx = canvas.getContext('2d')
if (!ctx) {
return null
}
ctx.drawImage(image, 0, 0)
const base64 = canvas.toDataURL('image/png')
callback(base64)
}
image.onerror = (err) => {
callback('')
}
},
}
./assets/image/1.jpg 项目中的静态资源图片
2.通过网络请求
img1: "https://img2.baidu.com/it/u=3443670360,1452319546&fm=253&fmt=auto&app=138&f=JPEG?w=761&h=500",
this.imgToBase64Http(this.img1,(base64)=>{
// 注意:图片很可能存在跨域问题,
this.img2 = base64
})
imgToBase64Http(url,callback) {
let xhr = new XMLHttpRequest();
xhr.open('get', url, true);
// 重点1
xhr.responseType = 'blob';
xhr.onload = function() {
if (this.status == 200) {
//得到一个blob对象
let blob = this.response;
// 重点2
let oFileReader = new FileReader();
oFileReader.onloadend = function(e) {
// 结果
const base64 = e.target.result
callback(base64)
};
oFileReader.readAsDataURL(blob);
}
};
xhr.send();
}
需要转化的图片很可能存在跨域问题,要么后端处理,要么前端处理。这里是使用时在vue中处理了跨域问题
devServer: { port: port, open: true, overlay: { warnings: false, errors: true }, proxy: { '/api': { target: 'http://-----:8084' changeOrigin: true, ws: true, pathRewrite: { '^/api': '' } } } },
使用图片路径:/api+图片剩余路径