Front-end implementation of image conversion to Base64

Without further ado, let’s get straight to the code.

base64 (url) {
      return new Promise((resolve) => {
        const image = new Image()
        // 先设置图片跨域属性
        image.crossOrigin = 'Anonymous'
        // 再给image赋值src属性,先后顺序不能颠倒
        image.src = url
        image.onload = function () {
          const canvas = document.createElement('CANVAS')
          // 设置canvas宽高等于图片实际宽高
          canvas.width = image.width
          canvas.height = image.height
          canvas.getContext('2d').drawImage(image, 0, 0)
          // toDataUrl可以接收2个参数,参数一:图片类型,参数二: 图片质量0-1(不传默认为0.92)
          const dataURL = canvas.toDataURL('image/jpeg')
          resolve(dataURL)
        }
        image.onerror = () => {
          resolve({ message: '相片处理失败' })
        }
      })
    },

We pass in a picture

async mounted () {
    // this.init()
    const url = await this.base64('https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg')
    console.log(url)
  },

Check the video address to see if it is successful. 

However, generally before we make such a request, we must process more than one picture, and then we need to process it in batches. However, this method is asynchronous. We need to convert the address of each object in an array into base64. It can truly complete our function. The data received by the front end from the back end is generally in this format.

 But we normally use map function traversal to convert the image address into base64, the above code:

 const newImgOBj = await Promise.all(this.imgOBj.map(async (item) => {
      return {
        name: item.name,
        img: await this.base64(item.img)
      }
    }))
    console.log(newImgOBj)

Print it and see the results and find that our image address has been changed to base64 encoding.

Finally, we can render the image normally using the img tag. Little knowledge: When the browser recognizes the same image address, the browser will only request the image resource once.​ 

Guess you like

Origin blog.csdn.net/weixin_63537474/article/details/133380515