js base64格式与图片互转
js base64转为图片格式
js直接设置img属性值为 图片的base64数据即可。
如:
document.getElementById('img').setAttribute('img', 'base64数据')
js 图片转base64格式
如:
let imgUrl = 'imgUrl'
function getBase64Image (image) {
let canvas = document.createCanvas('canvas')
canvas.width = image.width
canvas.height = image.height
let ctx = canvas.getContext('2d')
ctx.drawImage(image, 0, 0, image.width, image.height)
let imgStr = image.src.substring(image.src.lastIndexOf('.')+1).toLowerCase()
let dataUrl = canvas.toDataURL('image/' + imgStr)
return dataUrl
}
let img = new Image()
img.src = imgUrl
img.onload = function() {
let base64 = this.getBase64Image(img)
console.log(base64)
}