vuejs如何将本地图片转为base64编码

 主要代码:

    // 注意图片的,onload是异步的,如果要封装成工具函数,需要用promise包装一下
    imgToBase64(url) {
      return new Promise((resolve, reject) => {
        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')
          return resolve(base64)
        }
        image.onerror = (err) => {
          return reject(err);
        }
      })
    },

调用方法:

           const imgUrl = require('D:\a.png');
          // const imgUrl = result.photo  // 如果是接口返回的文件路径,去掉require
           this.imgToBase64(imgUrl).then(res => {
                if (res) {
                  console.log('生成的base64图片', res)
                  result.photoBase64 = res
                }
              }).catch(err => {
                console.log('这里是错误', err);
              });

你可能感兴趣的:(常用方法,js,vue,javascript,前端,js,vue)