nodejs文件夹下批量png图片转为tiff

1、node版本为v21.7.0

2、package.json下配置

复制代码
"resolutions": {
  "sharp": "^0.29.0"
}

代码如下

javascript 复制代码
const path = require('path')
const fs = require('fs')

const sourceDir = '/Users/Documents/study/testTransImage/PNG'
const targetDir = '/Users/Documents/study/testTransImage/TIFF'

const sharp = require('sharp');

// 转换图片格式的函数
async function convertImageFormat(inputFile, outputFile) {
    try {
        await sharp(inputFile)
            .toFormat('tif') // 转换为PNG格式,可以改为其他格式,如 'jpeg', 'webp' 等
            .toFile(outputFile);
        console.log('图片格式转换成功!');
    } catch (err) {
        console.error('转换过程中发生错误:', err);
    }
}


const isExist = (path) => { // 判断文件夹是否存在, 不存在创建一个
    if (!fs.existsSync(path)) {
        fs.mkdirSync(path)
    }
}

isExist(targetDir)

const copyFile = (sourcePath, targetPath) => {
    const sourceFile = fs.readdirSync(sourcePath, { withFileTypes: true })

    sourceFile.forEach(file => {
        const newSourcePath = path.resolve(sourcePath, file.name)
        const newTargetPath = path.resolve(targetPath, file.name)
        if (file.isDirectory()) {
            isExist(newTargetPath)
            copyFile(newSourcePath, newTargetPath)
        }
        if (file.name.endsWith('.png')) { // 需要复制其他的格式的文件修改 .mp4 既可
            //fs.copyFileSync(newSourcePath, newTargetPath.replace('.png','.tif'))
            // 使用示例
            convertImageFormat(newSourcePath, newTargetPath.replace('.png','.tif')) // 将JPG图片转换为PNG格式
            console.info(newTargetPath)
        }
    })
}

copyFile(sourceDir, targetDir)
相关推荐
英俊潇洒美少年1 分钟前
js 进程与线程的讲解
javascript
wheelmouse778832 分钟前
网络排查基础与实战指南:Ping 与 Telnet
开发语言·网络·php
敲代码的嘎仔1 小时前
Java后端开发——真实面试汇总(持续更新)
java·开发语言·程序人生·面试·职场和发展·八股
迈巴赫车主1 小时前
蓝桥杯20560逃离高塔
java·开发语言·数据结构·算法·职场和发展·蓝桥杯
dleei1 小时前
彻底淘汰老旧 SVG 插件:unplugin-icons 与 Tailwind CSS v4 自定义图标最佳实践
前端·程序员·前端框架
春日见1 小时前
E2E自驾规控30讲:导论
开发语言·驱动开发·git·matlab·计算机外设
wangchunting1 小时前
Jvm-垃圾收集器
java·开发语言·jvm
LlNingyu1 小时前
文艺复兴,什么是XSS,常见形式(二)
前端·安全·xss
沐知全栈开发2 小时前
PHP Math: 精通PHP中的数学函数与应用
开发语言
汉堡大王95272 小时前
# AI 终于能"干活"了——Function Calling 完全指南
javascript·人工智能·机器学习