The back end returns the conversion and display of various image forms on the front end

one,

The picture returned by the interface is displayed as follows: (viewed in the console) This picture (binary) is returned

 

However, when printing, what is returned is

 

The reason for the problem is that axios returns json text by default, and the binary image data is forcibly converted into json text.
Once the cause is found, the solution is easy to handle. We are in axios, the responseType default return data type is json, change it to return data type blob. The following code is a normal picture display. If the picture returned by the interface needs to be echoed into the van-uploader, refer to  van-uplaoder to save the file to the backend, and echo the data returned by the backend interface -CSDN blog

axios({

     method: 'get',

     url: 'XXXXX',

      headers: {

                   'xxx': xxxx, //Requires reference of token

            },

       responseType: 'arraybuffer',

})

       .then(res => {                 

             let url=window.URL.createObjectURL(new Blob([res.data], { type: 'image/png' })),

              //Directly assign the url to the src of img

       })

        .catch(err => {

               reject(err.data)

          })

Two, url, base64, blob, conversion between the three

1. url to base64

Principle: Use canvas.toDataURL API to convert to base64

function urlToBase64(url) {
      return new Promise ((resolve,reject) => {
        let image = new Image();
        image.onload = function() {
          let canvas = document.createElement('canvas');
          canvas.width = this.naturalWidth;
          canvas.height = this.naturalHeight;
          // 将图片插入画布并开始绘制
          canvas.getContext('2d').drawImage(image, 0, 0);
          // result
          let result = canvas.toDataURL('image/png')
          resolve(result);
        };
        // CORS 策略,会存在跨域问题https://stackoverflow.com/questions/20424279/canvas-todataurl-securityerror
        image.setAttribute("crossOrigin",'Anonymous');
        image.src = url;
        // 图片加载失败的错误处理
        image.onerror = () => {
          reject(new Error('urlToBase64 error'));
      };
    }

transfer

let imgUrL = `http://XXX.jpg`
urlToBase64(imgUrL).then(res => {
  // 转化后的base64图片地址
  console.log('base64', res)
})

2. base64 to blob

Principle: Use URL.createObjectURL to create a temporary URL for a blob object

function base64ToBlob ({b64data = '', contentType = '', sliceSize = 512} = {}) {
  return new Promise((resolve, reject) => {
    // 使用 atob() 方法将数据解码
    let byteCharacters = atob(b64data);
    let byteArrays = [];
    for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
      let slice = byteCharacters.slice(offset, offset + sliceSize);
      let byteNumbers = [];
      for (let i = 0; i < slice.length; i++) {
          byteNumbers.push(slice.charCodeAt(i));
      }
      // 8 位无符号整数值的类型化数组。内容将初始化为 0。
      // 如果无法分配请求数目的字节,则将引发异常。
      byteArrays.push(new Uint8Array(byteNumbers));
    }
    let result = new Blob(byteArrays, {
      type: contentType
    })
    result = Object.assign(result,{
      // 这里一定要处理一下 URL.createObjectURL
      preview: URL.createObjectURL(result),
      name: `XXX.png`
    });
    resolve(result)
  })
 }

transfer

let base64 = base64.split(',')[1]
base64ToBlob({b64data: base64, contentType: 'image/png'}).then(res => {
  // 转后后的blob对象
  console.log('blob', res)
})

3. blob to base64

Principle: Use fileReader's readAsDataURL to convert blob to base64

blobToBase64(blob) {
  return new Promise((resolve, reject) => {
    const fileReader = new FileReader();
    fileReader.onload = (e) => {
      resolve(e.target.result);
    };
    // readAsDataURL
    fileReader.readAsDataURL(blob);
    fileReader.onerror = () => {
      reject(new Error('blobToBase64 error'));
    };
  });
}

transfer

blobToBase64(blob).then(res => {
  // 转化后的base64
  console.log('base64', res)
})

Three, three display methods, which one is more elegant?

url: Generally speaking, it is recommended to use url to display pictures. If the field passed from the backend is an image path.

base64: If the picture is large and the color levels of the picture are rich, this method is not suitable, because the string encoded by Base64 is very large, which will obviously increase the size of the HTML page and affect the loading speed. If the picture is like loading or table lines, the size is extremely small, but it occupies an HTTP request, and it will be used in many places. It is very suitable for "base64: URL image" technology to optimize! .

blob: When the backend returns a specific image binary stream, as I said in the scene reproduction in the first part, the frontend uses the blob container to receive it. It would be better to display the image as a blob.


 

Guess you like

Origin blog.csdn.net/qq_43532275/article/details/128879906