VUE图片转Base64
// 把图片转为base64格式imageToBase64 () {let that = this //防止function里指代不明确let image = new Image()image.crossOrigin = ''image.src = this.imageUrlimage.onload = function () {that.base64 = that.$getBase64I...
·
// 把图片转为base64格式
imageToBase64 () {
let that = this //防止function里指代不明确
let image = new Image()
image.crossOrigin = ''
image.src = this.imageUrl
image.onload = function () {
that.base64 = that.$getBase64Image(image)
}
// 然后可以引用base64
},
其中的getBase64Image作为全局方法挂载
Vue.prototype.$getBase64Image = img => {
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)
let ext = img.src.substring(img.src.lastIndexOf('.') + 1).toLowerCase()
if (ext === 'jpg') {
ext = 'jpeg' //这个地方是由于如果是jpg, 他会识别成image/png
}
const dataURL = canvas.toDataURL('image/' + ext)
return dataURL
}
在HTML中引用base64图片可以如下操作
<img :src="base64" alt="" class="photo"/>
值得注意的是,这里的base64已经带有"data:image/jpeg;base64,",若写成下面样式
<img :src=" 'data:image/jpeg;base64,' + base64" alt="" class="photo"/>
则会显示net::ERR_FAILED错误
更多推荐
已为社区贡献1条内容
所有评论(0)