把图片的透明部分去掉

问题:
canvas裁剪的图把整个画布都剪下来了,但只要有元素的部分
在这里插入图片描述

// 图像处理

// 把图片的透明部分去掉
export function getImagesRealSize(dataUrl) {
  return new Promise((resolve, reject) => {
    // 将Base64解码为二进制数据
    let binaryString = atob(dataUrl.split(',')[1]); // 去除dataUrl的前部分(例如"data:image/png;base64,")
    let len = binaryString.length;
    let bytes = new Uint8Array(len);
    for (let i = 0; i < len; i++) {
      bytes[i] = binaryString.charCodeAt(i);
    }

    // 创建Blob对象
    let blob = new Blob([bytes], {
      type: 'image/png'
    });

    // 创建Image对象
    let img = new Image();
    img.onload = function () {
      // 创建Canvas并设置尺寸
      let canvas = document.createElement('canvas');
      let ctx = canvas.getContext('2d');
      canvas.width = img.width;
      canvas.height = img.height;

      // 将Image绘制到Canvas
      ctx.drawImage(img, 0, 0);

      // 获取像素数据
      let imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
      let data = imageData.data;
      let hasData = data.some(item => item !== 0); // 检查是否有非透明像素

      if (hasData) {
        // 确定非透明像素的边界
        let left = canvas.width,
          right = 0,
          top = canvas.height,
          bottom = 0;
        for (let y = 0; y < canvas.height; y++) {
          for (let x = 0; x < canvas.width; x++) {
            let index = (y * canvas.width + x) * 4;
            if (data[index + 3] !== 0) { // 检查alpha通道
              if (x < left) left = x;
              if (x > right) right = x;
              if (y < top) top = y;
              if (y > bottom) bottom = y;
            }
          }
        }

        // 裁剪Canvas到非透明区域
        canvas.width = right - left + 1;
        canvas.height = bottom - top + 1;
        ctx.drawImage(img, left, top, canvas.width, canvas.height, 0, 0, canvas.width, canvas.height);

        // 导出新的Base64图像数据URL
        let newBase64 = canvas.toDataURL();
        // 获取新的宽和高
        let newWidth = canvas.width;
        let newHeight = canvas.height;

        console.log("🚀 ~ ServersPlugin ~ returnnewPromise ~ newBase64:340", newBase64, newWidth, newHeight)
        resolve({
          base64: newBase64,
          width: newWidth,
          height: newHeight
        });
        // resolve(newBase64);
      } else {
        // 如果没有非透明像素,返回一个空白图像的Base64
        resolve('data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=');
      }
    };
    img.onerror = reject;
    img.src = URL.createObjectURL(blob);
  });
}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值