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)
相关推荐
Codebee2 分钟前
OneCode 移动套件多平台适配详细报告
前端·人工智能
你知唔知咩系timing啊4 分钟前
🎙️ 站在巨人肩膀上:基于 SenseVoice.cpp 的前端语音识别实践
前端
一位搞嵌入式的 genius5 分钟前
前端开发核心技术与工具全解析:从构建工具到实时通信
前端·笔记
littleplayer7 分钟前
Redux 中›ABC三个页面是如何通信的?
前端
安卓开发者7 分钟前
鸿蒙NEXT的Web组件网络安全与隐私保护实践
前端·web安全·harmonyos
程序员NEO16 分钟前
3分钟搞定Vue组件库
前端
程序员NEO19 分钟前
WebStorm代码一键美化
前端
大白同学42127 分钟前
【C++】C++11介绍(Ⅱ)
开发语言·c++
你怎么知道我是队长35 分钟前
C语言---存储类
c语言·开发语言
XIAOYU67201342 分钟前
金融数学专业需要学哪些数学和编程内容?
开发语言·matlab·金融