reduce-base64-img
TypeScript icon, indicating that this package has built-in type declarations

1.0.4 • Public • Published

reduce-base64-img

实际需求:

需要将完整的 HTML 代码片段完整传入桌面应用,但由于图片可能存在跨域问题,需要在网页端先把图片缩小并编码为 base64 的格式,这样实现在应用端的图片展示功能

实现功能:

封装的一个将图片压缩并编码为 base64 的方法,并异步获取编码后的图

具体实现:

  • @imgUrl 图片地址
  • @scale 图片缩小程度,设置范围 0~10,默认为 1
  • @isCrossOrigin 图片是否跨域,默认 false,一般不用传
getBase64(imgUrl, scale,isCrossOrigin) {
    let scaleVal = 1;
    if (scale && scale > 0 && scale <= 10) scaleVal = scale;
    return new Promise((reslove) => {
      // 通过构造函数来创建的 img 实例
      const Img = new Image(100 * scaleVal, 100 * scaleVal);
      Img.src = imgUrl;
      // 图片是否跨域请求
      isCrossOrigin ? Img.setAttribute("crossOrigin", "anonymous") : "";
      // 确保图片完整获取到,这是个异步事件
      Img.onload = () => {
        const canvas = document.createElement("canvas"); // 创建canvas元素
        const width = Img.width; // 图片压缩比列
        const height = Img.height;
        const ext = Img.src
          .substring(Img.src.lastIndexOf(".") + 1)
          .toLowerCase();
        canvas.width = width;
        canvas.height = height;
        canvas.getContext("2d").drawImage(Img, 0, 0, width, height); // 将图片绘制到canvas中
        const dataURL = canvas.toDataURL("image/" + ext); // 转换图片为dataURL
        reslove(dataURL);
      };
    }).catch((err) => err);
  }

Readme

Keywords

Package Sidebar

Install

npm i reduce-base64-img

Weekly Downloads

3

Version

1.0.4

License

ISC

Unpacked Size

3.44 kB

Total Files

4

Last publish

Collaborators

  • yandeli