搜索
首页web前端js教程聊聊怎么使用node实现一个图片拼接插件

聊聊怎么使用node实现一个图片拼接插件

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

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

聊聊怎么使用node实现一个图片拼接插件

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

插件效果

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

1、横向拼接两张图片

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

1.png

n1.jpg

2.png

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

3.png

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

4.png

3、批量拼接

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

5.png

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

6.png

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

7.png

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

8.png

插件实现

单张图片拼接

使用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 < fileList.length; index++) {
      let leftFile = path.join(folderPath, fileList[index - 1]);
      let rightFile = path.join(folderPath, fileList[index]);
      const leftPath = await this.resizeImage({
        path:leftFile,
        width:imgInfo.width,
        height:imgInfo.height
      });
      const rightPath = await this.resizeImage({
        path:rightFile,
        width:imgInfo.width,
        height:imgInfo.height
      });
      progressBarC.run(index);
      await this.collapse(index == 1 ? leftPath : targetFilePath,rightPath,targetFilePath,direction);
      fs.unlinkSync(leftPath);
      fs.unlinkSync(rightPath);
    }
    console.log(&#39;&#39;);
    return targetFilePath;
  }

自定义矩阵拼接

const gm = require(&#39;gm&#39;);
const fs = require(&#39;fs&#39;);
const path = require(&#39;path&#39;);
const progressBar = require(&#39;@jyeontu/progress-bar&#39;);
const {getFileSuffix,getMetadata,resizeImage} = require(&#39;./util&#39;);
async conCatByMaxit(res){
    const {shape} = res;
    const tmpList = [];
    const barConfig = {
      duration: shape[0].length * shape.length,
      current: 0,
      block:&#39;█&#39;,
      showNumber:true,
      tip:{
          0: &#39;拼接中……&#39;,
          100:&#39;拼接完成&#39;
      },
      color:&#39;green&#39;
    };
    const progressBarC = new progressBar(barConfig);
    let target = &#39;&#39;;
    let extensionName = getFileSuffix(shape[0][0], ".");
    const imgInfo = await this.getImgInfo(shape[0][0]);
    for(let i = 0; i < shape.length; i++){
      target = res.target + &#39;\\&#39; + `targetImg${i}.${extensionName}`;
      for(let j = 1; j < shape[i].length; j++){
        const leftPath = await this.resizeImage({
          path:shape[i][j - 1],
          width:imgInfo.width,
          height:imgInfo.height
        });
        const rightPath = await resizeImage({
          path:shape[i][j],
          width:imgInfo.width,
          height:imgInfo.height
        });
        tmpList.push(leftPath,rightPath,target);
        progressBarC.run(shape[i].length * i + j);
        await this.collapse(j == 1 ? leftPath : target,rightPath,target);
      }
      if( 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 < tmpList.length; i++){
      try{
        fs.unlinkSync(tmpList[i]);
      }catch(err){
        // console.error(err);
      }
    }
    console.log(&#39;&#39;);
    return newTarget;
}

插件使用

依赖引入

const consoleInput = require(&#39;@jyeontu/img-concat&#39;);
const ImgConcatClass = new ImgConcat();

横向拼接两张图片

参数说明

  • left

左边图片路径

  • right

右边图片路径

  • target

合成图片保存目录

示例代码

const p1 = {
    left:&#39;.\\img\\n1.jpg&#39;,
    right:&#39;.\\img\\n2.jpg&#39;,
    target:&#39;.\\longImg&#39;
}
// 横向拼接两张图片
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 教程

以上是聊聊怎么使用node实现一个图片拼接插件的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文转载于:掘金社区。如有侵权,请联系admin@php.cn删除
JavaScript数据类型:浏览器和nodejs之间是否有区别?JavaScript数据类型:浏览器和nodejs之间是否有区别?May 14, 2025 am 12:15 AM

JavaScript核心数据类型在浏览器和Node.js中一致,但处理方式和额外类型有所不同。1)全局对象在浏览器中为window,在Node.js中为global。2)Node.js独有Buffer对象,用于处理二进制数据。3)性能和时间处理在两者间也有差异,需根据环境调整代码。

JavaScript评论:使用//和 / * * / * / * /JavaScript评论:使用//和 / * * / * / * /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:开发人员的比较分析Python vs. JavaScript:开发人员的比较分析May 09, 2025 am 12:22 AM

Python和JavaScript的主要区别在于类型系统和应用场景。1.Python使用动态类型,适合科学计算和数据分析。2.JavaScript采用弱类型,广泛用于前端和全栈开发。两者在异步编程和性能优化上各有优势,选择时应根据项目需求决定。

Python vs. JavaScript:选择合适的工具Python vs. JavaScript:选择合适的工具May 08, 2025 am 12:10 AM

选择Python还是JavaScript取决于项目类型:1)数据科学和自动化任务选择Python;2)前端和全栈开发选择JavaScript。Python因其在数据处理和自动化方面的强大库而备受青睐,而JavaScript则因其在网页交互和全栈开发中的优势而不可或缺。

Python和JavaScript:了解每个的优势Python和JavaScript:了解每个的优势May 06, 2025 am 12:15 AM

Python和JavaScript各有优势,选择取决于项目需求和个人偏好。1.Python易学,语法简洁,适用于数据科学和后端开发,但执行速度较慢。2.JavaScript在前端开发中无处不在,异步编程能力强,Node.js使其适用于全栈开发,但语法可能复杂且易出错。

JavaScript的核心:它是在C还是C上构建的?JavaScript的核心:它是在C还是C上构建的?May 05, 2025 am 12:07 AM

javascriptisnotbuiltoncorc; saninterpretedlanguagethatrunsonenginesoftenwritteninc.1)javascriptwasdesignedAsalightweight,解释edganguageforwebbrowsers.2)Enginesevolvedfromsimpleterterterpretpreterterterpretertestojitcompilerers,典型地提示。

JavaScript应用程序:从前端到后端JavaScript应用程序:从前端到后端May 04, 2025 am 12:12 AM

JavaScript可用于前端和后端开发。前端通过DOM操作增强用户体验,后端通过Node.js处理服务器任务。1.前端示例:改变网页文本内容。2.后端示例:创建Node.js服务器。

Python vs. JavaScript:您应该学到哪种语言?Python vs. JavaScript:您应该学到哪种语言?May 03, 2025 am 12:10 AM

选择Python还是JavaScript应基于职业发展、学习曲线和生态系统:1)职业发展:Python适合数据科学和后端开发,JavaScript适合前端和全栈开发。2)学习曲线:Python语法简洁,适合初学者;JavaScript语法灵活。3)生态系统:Python有丰富的科学计算库,JavaScript有强大的前端框架。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

Atom编辑器mac版下载

Atom编辑器mac版下载

最流行的的开源编辑器

SublimeText3 英文版

SublimeText3 英文版

推荐:为Win版本,支持代码提示!

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

mPDF

mPDF

mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

Dreamweaver Mac版

Dreamweaver Mac版

视觉化网页开发工具