nodejs 基于sharp + smartcrop 实现图片的智能提取排版
  8KhYbgszLLmZ 2023年11月30日 22 0

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

简单任务描述

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

  • 参考代码
    package.json

 


{
  "name": "nodejs-images-sharp",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "dependencies": {
    "sharp": "^0.32.6",
    "smartcrop-sharp": "^2.0.8"
  }
}
"name": "nodejs-images-sharp",


utils.js 一个简单的工具类,利用了smartcrop-sharp 进行图片的智能提取并转换为一个标准大小的图片

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")
const smartcrop = require('smartcrop-sharp');

效果

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

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

模版填充效果

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

说明

实际上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
https://github.com/rongfengliang/sharp_smartcrop_learning

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月30日 0

暂无评论

推荐阅读
8KhYbgszLLmZ