js将图片转base64两种方法

2023年11月29日 1613点热度 0人点赞 0条评论

第一种:Image + canvas

const getBase64Image = src => {
    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)
        }
    })
}

 

第二种:xhr + FileReader

const 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()
    })
}

路灯

这个人很懒,什么都没留下

文章评论