亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

JS將圖片轉(zhuǎn)Base64的2種方法代碼

 更新時(shí)間:2024年05月09日 11:35:19   作者:山楂樹(shù)の  
這篇文章主要給大家介紹了關(guān)于JS將圖片轉(zhuǎn)Base64的2種方法,base64 其實(shí)是一種編碼轉(zhuǎn)換方式,將ASCII字符轉(zhuǎn)換成普通文本,是網(wǎng)絡(luò)上最常見(jiàn)的用于傳輸8Bit字節(jié)代碼的編碼方式之一,需要的朋友可以參考下

第一種:Blob和FileReader 對(duì)象

實(shí)現(xiàn)原理:
使用xhr請(qǐng)求圖片,并設(shè)置返回的文件類型為Blob對(duì)象[xhr.responseType = “blob”]
使用FileReader 對(duì)象接收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()

實(shí)現(xiàn)原理:
使用canvas.toDataURL()方法
需要解決圖片跨域問(wèn)題 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)
  }

附:需要轉(zhuǎn)化的圖片很可能存在跨域問(wèn)題,要么后端處理,要么前端處理。這里是使用時(shí)在vue中處理了跨域問(wèn)題 

  devServer: {
    port: port,
    open: true,
    overlay: {
      warnings: false,
      errors: true
    },
    proxy: {
      '/api': {
        target: 'http://-----:8084'
        changeOrigin: true,
        ws: true,
        pathRewrite: {
 
          '^/api': ''
        }
      }
    }
  },

總結(jié) 

到此這篇關(guān)于JS將圖片轉(zhuǎn)Base64的2種方法代碼的文章就介紹到這了,更多相關(guān)JS圖片轉(zhuǎn)Base64內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論