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)
相关推荐
水痕014 分钟前
nginx一个域名下部署多套前端项目
运维·前端·nginx
Anyin7 分钟前
Spring AI Alibaba - DeepResearch 前端主体 UI 构建
前端·ai编程·trae
微小冷7 分钟前
Vimba相机二次开发教程,基于Python
开发语言·python·二次开发·相机开发·vimba相机·vimba
非优秀程序员7 分钟前
8 个提升开发者效率的小众 AI 项目
前端·人工智能·后端
河畔一角15 分钟前
一些感悟
前端
从0至120 分钟前
C++编程入门:从基础到复合类型
开发语言·c++
excel21 分钟前
理解 JavaScript 中的 for...in 与 for...of 的区别
前端
前端小巷子1 小时前
Webpack 5模块联邦
前端·javascript·面试
玲小珑1 小时前
Next.js 教程系列(十九)图像优化:next/image 与高级技巧
前端·next.js
晓得迷路了1 小时前
栗子前端技术周刊第 91 期 - 新版 React Compiler 文档、2025 HTML 状态调查、Bun v1.2.19...
前端·javascript·react.js