nodejs 基于sharp + smartcrop 实现图片的智能提取排版

发布时间 2023-11-05 22:01:32作者: 荣锋亮

属于一个简单的demo 示例,主要是学习下sharp 包对于图片的处理,以及基于smartcrop.js 实现智能图片抠图
结合sharp提供的图片组合能力,实现一个基于模版的图片组合,代码很简单

简单任务描述

就是有一个图片,我们需要智能的提取核心信息,并生成一个确定大小的图片,然后基于将生成的图片填充到一个模版图片中
实现类似日常中大家的一寸照片生成效果

  • 参考代码
    utils.js 一个简单的工具类,利用了smartcrop-sharp 进行图片的智能提取并转换为一个标准大小的图片
 
const sharp = require('sharp');
const smartcrop = require('smartcrop-sharp');
 
function applySmartCrop(src, width, height) {
  return smartcrop.crop(src, { width: width, height: height })
    .then(function(result) {
      const crop = result.topCrop;
      return sharp(src)
        .extract({ width: crop.width, height: crop.height, left: crop.x, top: crop.y })
        .resize(width, height)
        .toBuffer();
    })
}
 
module.exports = {
  applySmartCrop
};

com.js 基于组合能力进行图片的模版填充,位置部分使用了硬编码,实际可以自己调整

const sharp = require('sharp');
const util = require('./utils')
 
async function templateImage(source, width, height, output) {
    let smartcrop = await util.applySmartCrop(source, width, height)
    let items = [
        {
            input: smartcrop,
            top: 25,
            left: 25,
        },
        {
            input: smartcrop,
            top: 25,
            left: 340,
        },
        {
            input: smartcrop,
            top: 25,
            left: 655,
        },
        {
            input: smartcrop,
            top: 360,
            left: 25,
        },
        {
            input: smartcrop,
            top: 360,
            left: 340,
        },
        {
            input: smartcrop,
            top: 360,
            left: 655,
        },
        {
            input: smartcrop,
            top: 700,
            left: 25,
        },
        {
            input: smartcrop,
            top: 700,
            left: 340,
        },
        {
            input: smartcrop,
            top: 700,
            left: 655,
        }
    ];
    sharp("template.png").composite(items)
        .toFile(output)
}
 
templateImage("v3.png", 283, 300, "output.png")

效果

实际图片是一个非规则,长度比较大的图片

 

模版填充效果

说明

实际上sharp 也包含一个简单的智能裁剪方法,但是不是很好,比如smartcrop-sharp,所以利用几个工具的集成,可以实现一个相对可靠的智能裁剪,以及模版填充,当然也可以自己集合业务处理加上智能裁剪进行原始图片的处理(比如用户选择需要裁剪的部分图片,然后再利用库进行一些处处理,同时也可以添加一些其他抠图算法),实现更加灵活的图片处理

参考资料

https://github.com/lovell/sharp
https://github.com/libvips/libvips
https://github.com/jwagner/smartcrop.js
https://sharp.pixelplumbing.com/api-composite
https://github.com/jwagner/smartcrop-sharp