You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Jimp中将图片黑色区域转换为透明?

使用Jimp.js将图片黑色区域转为透明

核心实现思路

遍历图片每一个像素,判断像素是否为黑色(或接近黑色),将符合条件的像素的alpha通道设为0(完全透明)。

代码实现

const Jimp = require('jimp');

async function convertBlackToTransparent(inputPath, outputPath, tolerance = 0) {
  // 读取目标图片
  const image = await Jimp.read(inputPath);

  // 遍历所有像素
  image.scan(0, 0, image.bitmap.width, image.bitmap.height, function(x, y, idx) {
    // 获取当前像素的RGB值
    const red = this.bitmap.data[idx + 0];
    const green = this.bitmap.data[idx + 1];
    const blue = this.bitmap.data[idx + 2];

    // 判断是否为黑色(支持容差配置)
    const isBlack = red <= tolerance && green <= tolerance && blue <= tolerance;

    if (isBlack) {
      // 将alpha通道设为0,实现透明
      this.bitmap.data[idx + 3] = 0;
    }
  });

  // 保存处理后的图片
  await image.writeAsync(outputPath);
  console.log('处理完成,结果已保存至', outputPath);
}

// 调用示例:第三个参数为容差值,可处理接近黑色的深色区域
convertBlackToTransparent('./input.png', './output.png', 10);

关键说明

  • tolerance 参数:默认值为0,仅处理纯黑(RGB均为0)的区域;设置大于0的值时,会将RGB值均小于该阈值的深色区域转为透明,按需调整即可。
  • image.scan() 是Jimp内置的像素遍历方法,像素数据数组以RGBA顺序存储,idx 为当前像素的起始索引。
  • 确保输入图片支持alpha通道(如PNG格式),若为JPG等无透明通道的格式,需先转换为PNG再进行处理。

内容的提问来源于stack exchange,提问作者miguel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 09:25:25