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)
相关推荐
excel1 分钟前
Vue 编译核心:transformModel 深度解析
前端
excel1 分钟前
Vue 编译器源码精解:transformOnce 的实现与原理解析
前端
前端架构师-老李1 分钟前
React中useContext的基本使用和原理解析
前端·javascript·react.js
Moonbit3 分钟前
招募进行时 | MoonBit AI : 程序语言 & 大模型
前端·后端·面试
excel4 分钟前
Vue 3 编译器源码深度解析:transformOn —— v-on 指令的编译过程
前端
excel7 分钟前
Vue 编译器核心:transformIf 模块深度解析
前端
CodeToGym12 分钟前
Vue2 和 Vue3 生命周期的理解与对比
前端·javascript·vue.js
excel14 分钟前
深度解析 Vue 编译器源码:transformFor 的实现原理
前端
excel15 分钟前
Vue 编译器源码精读:transformBind —— v-bind 指令的编译核心
前端
excel17 分钟前
深入浅出:Vue 编译器中的 transformText —— 如何把模板文本变成高效的渲染代码
前端