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)
相关推荐
蒲公英1001几秒前
vue3学习:axios输入城市名称查询该城市天气
前端·vue.js·学习
程序猿小D1 分钟前
第二百六十九节 JPA教程 - JPA查询OrderBy两个属性示例
java·开发语言·数据库·windows·jpa
阿华的代码王国9 分钟前
【JavaEE】——文件IO的应用
开发语言·python
satan–015 分钟前
R语言的下载、安装及环境配置(Rstudio&VSCode)
开发语言·windows·vscode·r语言
以对_23 分钟前
uview表单校验不生效问题
前端·uni-app
电饭叔1 小时前
《python语言程序设计》2018版第8章19题几何Rectangle2D类(下)-头疼的几何和数学
开发语言·python
Eternal-Student1 小时前
everyday_question dq20240731
开发语言·arm开发·php
卑微求AC1 小时前
(C语言贪吃蛇)11.贪吃蛇方向移动和刷新界面一起实现面临的问题
c语言·开发语言
Zheng1131 小时前
【可视化大屏】将柱状图引入到html页面中
javascript·ajax·html
程序猿小D1 小时前
第二百六十七节 JPA教程 - JPA查询AND条件示例
java·开发语言·前端·数据库·windows·python·jpa