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)
相关推荐
Hello--_--World9 分钟前
ES13:类私有属性和方法、顶层 await、at() 方法、Object.hasOwnProperty()、类静态块 相关知识点
开发语言·javascript·es13
Hugh-Yu-13012317 分钟前
二元一次方程组求解器c++代码
开发语言·c++·算法
weixin_5206498723 分钟前
C#进阶-特性全知识点总结
开发语言·c#
文祐24 分钟前
C++类之虚函数表及其内存布局
开发语言·c++
comerzhang65530 分钟前
Web 性能的架构边界:跨线程信令通道的确定性分析
javascript·webassembly
Hooray33 分钟前
为了在 Vue 项目里用上想要的 React 组件,我写了这个 skill
前端·ai编程
咸鱼翻身了么35 分钟前
模仿ai数据流 开箱即用
前端
风花雪月_35 分钟前
🔥IntersectionObserver:前端性能优化的“隐形监工”
前端
Bigger35 分钟前
告别 AI 塑料感:我是如何用 frontend-design skill 重塑项目官网的
前端·ai编程·trae
发际线向北35 分钟前
0x02 Android DI 框架解析之Hilt
前端