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

Node.js Sharp库如何利用多边形蒙版合并两张图片?

用Sharp实现多边形遮罩合并图片

要实现多边形区域显示image1、其余区域显示image2的效果,我们可以借助Sharp的SVG遮罩和图像合成能力完成,具体实现如下:

完整函数实现

const sharp = require('sharp');

async function mergeImagesWithPolygonMask(image1, image2, polygon) {
  // 获取第一张图的尺寸,确保两张图尺寸一致
  const { width, height } = await image1.metadata();
  
  // 将多边形坐标转为SVG路径字符串(M起点,L连接各点,Z闭合路径)
  const polygonPath = `M ${polygon.map(pt => `${pt[0]} ${pt[1]}`).join(' L ')} Z`;
  
  // 生成正遮罩:多边形区域为白色(保留像素),其余为黑色(剔除像素)
  const maskSvg = `
    <svg width="${width}" height="${height}">
      <rect width="${width}" height="${height}" fill="black"/>
      <path d="${polygonPath}" fill="white"/>
    </svg>
  `;
  
  // 处理image1:仅保留多边形内的像素
  const maskedImage1 = image1.clone().composite([{
    input: Buffer.from(maskSvg),
    blend: 'dest-in'
  }]);
  
  // 生成反遮罩:多边形区域为黑色(剔除像素),其余为白色(保留像素)
  const inverseMaskSvg = `
    <svg width="${width}" height="${height}">
      <rect width="${width}" height="${height}" fill="white"/>
      <path d="${polygonPath}" fill="black"/>
    </svg>
  `;
  // 处理image2:仅保留多边形外的像素,同时对齐尺寸
  const maskedImage2 = image2.clone().resize(width, height).composite([{
    input: Buffer.from(inverseMaskSvg),
    blend: 'dest-in'
  }]);
  
  // 合并两张处理后的图:将image1的多边形区域叠加到image2上
  return maskedImage2.composite([{
    input: await maskedImage1.toBuffer(),
    blend: 'over'
  }]);
}

// 使用示例
async function run() {
  const image1 = sharp('image1.jpg');
  const image2 = sharp('image2.jpg');
  const polygon = [[0,0], [0, 100], [100, 100], [100, 0]];
  
  const newImage = await mergeImagesWithPolygonMask(image1, image2, polygon);
  await newImage.toFile('out.jpg');
}

run().catch(err => console.error(err));

核心逻辑说明

  • 尺寸对齐:以image1的尺寸为基准,将image2调整为相同大小,避免合成错位
  • SVG遮罩运用:
    • 正遮罩配合dest-in模式,只保留image1中多边形范围内的像素
    • 反遮罩配合dest-in模式,只保留image2中多边形范围外的像素
  • 图像合成:把处理后的image1叠加到处理后的image2上,得到最终的混合效果

如果你的多边形坐标是相对比例值,需要先转换为对应图片的绝对像素值再生成SVG路径。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 05:48:24