Image format conversion Image conversion to base64 format

In our daily projects, sometimes we need to convert pictures into base64 format. The following method can convert local pictures and network pictures into base64 format.

First of all, the first step, we need to instantiate a canvas, because we use canvas to achieve format conversion

It can be instantiated like this in a Vue project:

<canvas v-show="false"></canvas>

In other projects like this:

<canvas style="dispaly:node"></canvas>

Then comes the core part;

// 图片转为base64格式
export const imageToBase64 = (url, ext, callback) => {
  let canvas = document.createElement('canvas'); // 创建canvas DOM元素
  const ctx = canvas.getContext('2d');
  // eslint-disable-next-line no-var
  const img = new Image();
  img.crossOrigin = 'Anonymous';
  img.src = url;
  img.onload = function () {
    canvas.width = img.width ;
    canvas.height = img.height;
    ctx.drawImage(img, 0, 0, img.height, img.width); // 参数可自定义
    // eslint-disable-next-line no-shadow
    const dataURL = canvas.toDataURL(`image/${ext}`);
    callback(dataURL); // 回掉函数获取Base64编码
    canvas = null;
  };
};

When last used:

 imageToBase64(
        `${window.location.origin}${imgUrl}`,
        'jpg',
        (base64) => {
            
          }
)

Guess you like

Origin blog.csdn.net/weixin_49014702/article/details/125223863