Table of Contents
插件效果
横向拼接两张图片
纵向拼接两张图片
批量拼接
3.1 横向拼接长图
3.2 纵向拼接长图
自定义拼接矩阵
插件实现
单张图片拼接
自定义矩阵拼接
插件使用
依赖引入
参数说明
示例代码
源码地址
Home Web Front-end JS Tutorial Let's talk about how to use node to implement a picture splicing plug-in

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

Aug 02, 2022 pm 09:12 PM
nodejs nodejs​ node

怎么使用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}`);
});
Copy after login
  • 效果

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}`);
});
Copy after login
  • 效果

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}`);
})
Copy after login
  • 效果

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}`);
})
Copy after login
  • 效果

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}`);
});
Copy after login
  • 效果

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();
      })
    })
}
Copy after login

批量拼接

  • 使用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();
Copy after login

横向拼接两张图片

参数说明

  • left

左边图片路径

  • right

右边图片路径

  • target

合成图片保存目录

示例代码

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

纵向拼接两张图片

参数说明

  • left

左边图片路径

  • right

右边图片路径

  • target

合成图片保存目录

示例代码

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

批量拼接

参数说明

  • 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}`);
})
Copy after login

自定义拼接矩阵

参数说明

  • 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}`);
});
Copy after login

源码地址

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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

The difference between nodejs and tomcat The difference between nodejs and tomcat Apr 21, 2024 am 04:16 AM

The main differences between Node.js and Tomcat are: Runtime: Node.js is based on JavaScript runtime, while Tomcat is a Java Servlet container. I/O model: Node.js uses an asynchronous non-blocking model, while Tomcat is synchronous blocking. Concurrency handling: Node.js handles concurrency through an event loop, while Tomcat uses a thread pool. Application scenarios: Node.js is suitable for real-time, data-intensive and high-concurrency applications, and Tomcat is suitable for traditional Java web applications.

The difference between nodejs and vuejs The difference between nodejs and vuejs Apr 21, 2024 am 04:17 AM

Node.js is a server-side JavaScript runtime, while Vue.js is a client-side JavaScript framework for creating interactive user interfaces. Node.js is used for server-side development, such as back-end service API development and data processing, while Vue.js is used for client-side development, such as single-page applications and responsive user interfaces.

Is nodejs a backend framework? Is nodejs a backend framework? Apr 21, 2024 am 05:09 AM

Node.js can be used as a backend framework as it offers features such as high performance, scalability, cross-platform support, rich ecosystem, and ease of development.

How to connect nodejs to mysql database How to connect nodejs to mysql database Apr 21, 2024 am 06:13 AM

To connect to a MySQL database, you need to follow these steps: Install the mysql2 driver. Use mysql2.createConnection() to create a connection object that contains the host address, port, username, password, and database name. Use connection.query() to perform queries. Finally use connection.end() to end the connection.

What is the difference between npm and npm.cmd files in the nodejs installation directory? What is the difference between npm and npm.cmd files in the nodejs installation directory? Apr 21, 2024 am 05:18 AM

There are two npm-related files in the Node.js installation directory: npm and npm.cmd. The differences are as follows: different extensions: npm is an executable file, and npm.cmd is a command window shortcut. Windows users: npm.cmd can be used from the command prompt, npm can only be run from the command line. Compatibility: npm.cmd is specific to Windows systems, npm is available cross-platform. Usage recommendations: Windows users use npm.cmd, other operating systems use npm.

Is nodejs a back-end development language? Is nodejs a back-end development language? Apr 21, 2024 am 05:09 AM

Yes, Node.js is a backend development language. It is used for back-end development, including handling server-side business logic, managing database connections, and providing APIs.

What are the global variables in nodejs What are the global variables in nodejs Apr 21, 2024 am 04:54 AM

The following global variables exist in Node.js: Global object: global Core module: process, console, require Runtime environment variables: __dirname, __filename, __line, __column Constants: undefined, null, NaN, Infinity, -Infinity

Is there a big difference between nodejs and java? Is there a big difference between nodejs and java? Apr 21, 2024 am 06:12 AM

The main differences between Node.js and Java are design and features: Event-driven vs. thread-driven: Node.js is event-driven and Java is thread-driven. Single-threaded vs. multi-threaded: Node.js uses a single-threaded event loop, and Java uses a multi-threaded architecture. Runtime environment: Node.js runs on the V8 JavaScript engine, while Java runs on the JVM. Syntax: Node.js uses JavaScript syntax, while Java uses Java syntax. Purpose: Node.js is suitable for I/O-intensive tasks, while Java is suitable for large enterprise applications.

See all articles