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)
相关推荐
三门6 分钟前
vue官网新读之后收获记录
前端
Keepreal49613 分钟前
使用Canvas绘制转盘
javascript·vue.js·canvas
mapbar_front19 分钟前
我们需要前端架构师这个职位吗?
前端
纵横八荒25 分钟前
Java基础加强13-集合框架、Stream流
java·开发语言
ScriptBIN27 分钟前
Javaweb--Vue
前端·vue.js
KenXu31 分钟前
React Conf 2025 - 核心更新
前端
前端Hardy35 分钟前
Vue 高效开发技巧合集:10 个实用技巧让代码简洁 50%+,面试直接加分!
前端·javascript·vue.js
欣然~1 小时前
百度地图收藏地址提取与格式转换工具 说明文档
java·开发语言·dubbo
ᖰ・◡・ᖳ1 小时前
JavaScript:神奇的ES6之旅
前端·javascript·学习·es6
William_cl1 小时前
C# MVC 修复DataTable时间排序以及中英文系统的时间筛选问题
开发语言·c#·mvc