From 9767e2c229d304cc8af89a48a551d35b81a6fe3e Mon Sep 17 00:00:00 2001 From: lichaojun Date: Tue, 1 Oct 2024 23:37:30 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20doc=E6=8B=BC=E5=9B=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/doc_img_merge.js | 58 ++++++++++++++++++++++++++++++++++++++++ src/product_cover_img.js | 10 ++++--- 2 files changed, 64 insertions(+), 4 deletions(-) create mode 100644 src/doc_img_merge.js diff --git a/src/doc_img_merge.js b/src/doc_img_merge.js new file mode 100644 index 0000000..ed96fda --- /dev/null +++ b/src/doc_img_merge.js @@ -0,0 +1,58 @@ +const fs = require('fs'); +const path = require('path'); +const sharp = require('sharp'); +const { getInputDir } = require('../utils/index'); + +//工作目录文件夹路径 +const inputDir = 'E:/商品资料汇总/商品资料(1051-1100)/doc1089-英语小报'; //getInputDir(); +// 父文件夹路径 +const parentFolder = `${inputDir}/预览图`; +if (!inputDir) { + console.log('未执行手抄报拼图功能,工作目录不存在'); + return; +} + +async function processImages(folderPath) { + // 读取文件夹内的所有子文件夹 + const subFolders = fs.readdirSync(folderPath); + for (const subFolder of subFolders) { + const subFolderPath = path.join(folderPath, subFolder); + const stats = fs.statSync(subFolderPath); + + // 确保是文件夹 + if (stats.isDirectory()) { + const images = fs.readdirSync(subFolderPath); + const imagePaths = images.map((image) => path.join(subFolderPath, image)).filter((img) => img.endsWith('.jpg') || img.endsWith('.png')); + + if (imagePaths.length === 2) { + // 使用 sharp 拼接图片 + const [image1, image2] = imagePaths; + // 获取第一张图片的高度 + const { width, height } = await sharp(image1).metadata(); + const outputImagePath = path.join(folderPath, `${subFolder}.png`); + + await sharp({ + create: { + width: width, // 宽度使用第一张图片的宽度 + height: height * 2, // 高度为两张图片的总高度 + channels: 4, + background: { r: 255, g: 255, b: 255, alpha: 0 }, // 背景透明 + }, + }) + .composite([ + { input: await sharp(image1).toBuffer(), top: 0, left: 0 }, + { input: await sharp(image2).toBuffer(), top: height, left: 0 }, + ]) + .toFile(outputImagePath); + + console.log(`合并完成: ${outputImagePath}`); + } else { + console.log(`跳过文件夹 ${subFolder}: 找不到两张图片`); + } + } + } +} + +// 替换为你自己的文件夹路径 +// const folderPath = './your-folder-path'; +processImages(parentFolder).catch((err) => console.error(err)); diff --git a/src/product_cover_img.js b/src/product_cover_img.js index d99dfd8..5a76590 100644 --- a/src/product_cover_img.js +++ b/src/product_cover_img.js @@ -45,12 +45,14 @@ async function resizeImage(imageDir, outputDir, scale) { } //读取输入目录下所有文件 -fs.readdirSync(previewDir).forEach(async (file, index) => { - if (index > 4) { - return; - } +let execNum = 0; +fs.readdirSync(previewDir).forEach(async (file) => { const ext = file.split('.').pop().toLowerCase(); if (cover.imgFormat.has(ext)) { + execNum++; + if (execNum > 5) { + return; + } const inputPath = path.join(previewDir, file); cover.scaleArr.forEach((item) => { const outputPath = path.join(item.dir, file);