图片转为base64格式

需求: echarts树图做组织架构的展示, 原有图为方向, 前端将图转为圆形展示.

import React, { useEffect, useState } from "react";
import "./styles.css";
import _ from "lodash";

const toDataURL = (src) => {
  const fun = (resolve) => {
    const img = new Image();
    const type = _.findLast(src.split(".")) || "png";
    img.crossOrigin = "anonymous";
    // eslint-disable-next-line func-names
    img.onload = function () {
      const canvas = document.createElement("CANVAS");
      const circleCtx = canvas.getContext("2d");
      canvas.height = img.height;
      canvas.width = img.width;
      const diameter = Math.min(img.height, img.width);
      const raduis = diameter / 2;
      circleCtx.save();
      circleCtx.beginPath();
      // 将图片绘制成圆形
      circleCtx.arc(raduis, raduis, raduis, 0, Math.PI * 2, false);
      circleCtx.strokeStyle = "#2465D3";
      circleCtx.stroke();
      circleCtx.clip();
      circleCtx.drawImage(img, 0, 0, diameter, diameter);
      circleCtx.restore();
      // jpeg的数据有个黑色的背景 将jpeg强制显示成png
      const dataURL = canvas.toDataURL(
        `image/${type === "jpeg" ? "png" : type}`
      );
      resolve({ dataURL });
    };
    img.src = src;
  };
  return new Promise(fun);
};

export default function App() {
  const [base64Img, setBase64Img] = useState([]);
  useEffect(() => {
    // 网上随便找的图片
    const imglist = [
      "https://t7.baidu.com/it/u=1595072465,3644073269&fm=193&f=GIF",
      "https://t7.baidu.com/it/u=860330160,4117395242&fm=193&f=GIF"
    ];
    const base64ImgPromise = imglist.map((el) => {
      return toDataURL(el);
    });
    Promise.all(base64ImgPromise).then((imgres) => {
      // imgres base64格式图片合集
      setBase64Img(imgres);
    });
  }, []);

  return (
    <div className="App">
      {base64Img.map((el) => (
        <img src={el.dataURL} width="200" />
      ))}
    </div>
  );
}

:

  1. 图片跨域: 设置crossOrigin 为anonymous, 同事图片所在服务器也需要设置Access-Control-Allow-Methods
  2. 图片加载异步的问题

效果预览

posted @ 2022-12-02 10:11  VictoriaC~  阅读(97)  评论(0编辑  收藏  举报