search
HomeWeb Front-endJS TutorialLet's talk about how to use node to implement a picture splicing plug-in

怎么使用node实现一个图片拼接插件?下面本篇文章给大家介绍一下使用node封装一个图片拼接插件的方法,希望对大家有所帮助!

Let's talk about how to use node to implement a picture splicing plug-in

平时我们拼接图片的时候一般都要通过ps或者其他图片处理工具来进行处理合成,这次有个需求就需要进行图片拼接,而且我希望是可以直接使用代码进行拼接,于是就有了这么一个工具包。

插件效果

通过该插件,我们可以将图片进行以下操作:

1、横向拼接两张图片

如下,我们有这么两张图片,现在我们可以通过该工具将它们拼接成一张

Lets talk about how to use node to implement a picture splicing plug-in

n1.jpg

Lets talk about how to use node to implement a picture splicing plug-in

n2.jpg

  • 代码
const consoleInput = require('@jyeontu/img-concat');
const ImgConcatClass = new ImgConcat();
const p1 = {
    left:'.\\img\\n1.jpg',
    right:'.\\img\\n2.jpg',
    target:'.\\longImg'
}
// 横向拼接两张图片
ImgConcatClass.collapseHorizontal(p1).then(res=>{
    console.log(`拼接完成,图片路径为${res}`);
});
  • 效果

Lets talk about how to use node to implement a picture splicing plug-in

2、纵向拼接两张图片

仍是上面的两张图片,我们将其进行纵向拼接

  • 代码
const consoleInput = require('@jyeontu/img-concat');
const ImgConcatClass = new ImgConcat();
const p1 = {
    left:'.\\img\\n1.jpg',
    right:'.\\img\\n2.jpg',
    target:'.\\longImg'
}
//纵向拼接两张图片
ImgConcatClass.collapseVertical(p1).then(res=>{
    console.log(`拼接完成,图片路径为${res}`);
});
  • 效果

Lets talk about how to use node to implement a picture splicing plug-in

3、批量拼接

我们也可以直接将某一目录中的所有图片进行批量拼接成长图,如下图,我们现在要对该目录下的所有图片进行拼接:

Lets talk about how to use node to implement a picture splicing plug-in

3.1 横向拼接长图

  • 代码
const consoleInput = require('@jyeontu/img-concat');
const ImgConcatClass = new ImgConcat();
const p = {
    folderPath:'.\\img',        //资源目录
    targetFolder:'.\\longImg',  //转换后图片存放目录
    direction:'y'               //拼接方向,y为横向,n为纵向
}
// 拼接目录下的所有图片
ImgConcatClass.concatAll(p).then(res=>{
    console.log(`拼接完成,图片路径为${res}`);
})
  • 效果

Lets talk about how to use node to implement a picture splicing plug-in

3.2 纵向拼接长图

  • 代码
const consoleInput = require('@jyeontu/img-concat');
const ImgConcatClass = new ImgConcat();
const p = {
    folderPath:'.\\img',        //资源目录
    targetFolder:'.\\longImg',  //转换后图片存放目录
    direction:'n'               //拼接方向,y为横向,n为纵向
}
// 拼接目录下的所有图片
ImgConcatClass.concatAll(p).then(res=>{
    console.log(`拼接完成,图片路径为${res}`);
})
  • 效果

Lets talk about how to use node to implement a picture splicing plug-in

4、自定义拼接矩阵

我们也可以自己定义图片拼接矩阵,shape为二维数组,定义各个位置的图片,具体如下:

  • 代码
const consoleInput = require('@jyeontu/img-concat');
const ImgConcatClass = new ImgConcat();
const p = {
    shape:[['.\\img\\n1.jpg','.\\img\\white.jpg','.\\img\\n2.jpg'],
            ['.\\img\\white.jpg','.\\img\\n3.jpg','.\\img\\white.jpg'],
            ['.\\img\\n4.jpg','.\\img\\white.jpg','.\\img\\n5.jpg']
        ],
    target:'.\\longImg'
};
//自定义矩阵拼接图片
ImgConcatClass.conCatByMaxit(p).then(res=>{
    console.log(`拼接完成,图片路径为${res}`);
});
  • 效果

Lets talk about how to use node to implement a picture splicing plug-in

插件实现

单张图片拼接

使用GraphicsMagick进行图片拼接

const gm = require('gm');
collapse (left,right,target,flag = true) { 
    return new Promise((r) => {
      gm(left).append(right,flag).write(target, err => {
            if(err) console.log(err);
            r();
      })
    })
}

批量拼接

  • 使用sharp.js获取图片信息,调整图片分辨率大小
  • 使用fs获取文件列表
  • 使用path拼接文件路径
  • 使用 @jyeontu/progress-bar打印进度条
const gm = require('gm');
const fs = require('fs');
const path = require('path');
const progressBar = require('@jyeontu/progress-bar');
const {getFileSuffix,getMetadata,resizeImage} = require('./util');

doConcatAll = async(folderPath,targetFolder,direction) => { 
    let fileList = fs.readdirSync(folderPath);
    fileList.sort((a, b) => {
      return path.basename(a) - path.basename(b);
    });
    const extensionName = getFileSuffix(fileList[0], ".");
    let targetFilePath = path.join(targetFolder, new Date().getTime() + '.' + extensionName);
    const barConfig = {
      duration: fileList.length - 1,
      current: 0,
      block:'█',
      showNumber:true,
      tip:{
          0: '拼接中……',
          100:'拼接完成'
      },
      color:'green'
    };
    let progressBarC = new progressBar(barConfig);
    const imgInfo = await this.getImgInfo(path.join(folderPath, fileList[0]));
    for (let index = 1; index <h3 id="strong-自定义矩阵拼接-strong"><strong>自定义矩阵拼接</strong></h3><pre class="brush:php;toolbar:false">const gm = require('gm');
const fs = require('fs');
const path = require('path');
const progressBar = require('@jyeontu/progress-bar');
const {getFileSuffix,getMetadata,resizeImage} = require('./util');
async conCatByMaxit(res){
    const {shape} = res;
    const tmpList = [];
    const barConfig = {
      duration: shape[0].length * shape.length,
      current: 0,
      block:'█',
      showNumber:true,
      tip:{
          0: '拼接中……',
          100:'拼接完成'
      },
      color:'green'
    };
    const progressBarC = new progressBar(barConfig);
    let target = '';
    let extensionName = getFileSuffix(shape[0][0], ".");
    const imgInfo = await this.getImgInfo(shape[0][0]);
    for(let i = 0; i  0){
          await this.collapse(res.target + '\\' + `targetImg${i - 1}.${extensionName}`,target,target,false);
      }
    }
    progressBarC.run(shape[0].length * shape.length);
    const newTarget = res.target + '\\' + new Date().getTime() + `.${extensionName}`;
    fs.renameSync(target,newTarget)
    for(let i = 0; i <h2 id="strong-插件使用-strong"><strong>插件使用</strong></h2><h3 id="strong-依赖引入-strong"><strong>依赖引入</strong></h3><pre class="brush:php;toolbar:false">const consoleInput = require('@jyeontu/img-concat');
const ImgConcatClass = new ImgConcat();

横向拼接两张图片

参数说明

  • left

左边图片路径

  • right

右边图片路径

  • target

合成图片保存目录

示例代码

const p1 = {
    left:'.\\img\\n1.jpg',
    right:'.\\img\\n2.jpg',
    target:'.\\longImg'
}
// 横向拼接两张图片
ImgConcatClass.collapseHorizontal(p1).then(res=>{
    console.log(`拼接完成,图片路径为${res}`);
});

纵向拼接两张图片

参数说明

  • left

左边图片路径

  • right

右边图片路径

  • target

合成图片保存目录

示例代码

const p1 = {
    left:'.\\img\\n1.jpg',
    right:'.\\img\\n2.jpg',
    target:'.\\longImg'
}
// 纵向拼接两张图片
ImgConcatClass.collapseVertical(p1).then(res=>{
    console.log(`拼接完成,图片路径为${res}`);
});

批量拼接

参数说明

  • folderPath

资源文件目

  • targetFolder

合并图片保存目录

  • direction

图片合并方向,y为横向,n为纵向

示例代码

const consoleInput = require('@jyeontu/img-concat');
const ImgConcatClass = new ImgConcat();
const p = {
    folderPath:'.\\img',        //资源目录
    targetFolder:'.\\longImg',  //合并后图片存放目录
    direction:'y'               //拼接方向,y为横向,n为纵向
}
// 拼接目录下的所有图片
ImgConcatClass.concatAll(p).then(res=>{
    console.log(`拼接完成,图片路径为${res}`);
})

自定义拼接矩阵

参数说明

  • shape

图片合并矩阵,传入各个位置的图片路径。

  • target

合并后图片的保存路径

示例代码

const p = {
    shape:[['.\\img\\n1.jpg','.\\img\\white.jpg','.\\img\\n2.jpg'],
            ['.\\img\\white.jpg','.\\img\\n3.jpg','.\\img\\white.jpg'],
            ['.\\img\\n4.jpg','.\\img\\white.jpg','.\\img\\n5.jpg']
        ],
    target:'.\\longImg'
};
//自定义矩阵拼接图片
ImgConcatClass.conCatByMaxit(p).then(res=>{
    console.log(`拼接完成,图片路径为${res}`);
});

源码地址

https://gitee.com/zheng_yongtao/node-scripting-tool/tree/master/src/imgConcat

更多node相关知识,请访问:nodejs 教程

The above is the detailed content of Let's talk about how to use node to implement a picture splicing plug-in. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools