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)
相关推荐
new code Boy4 分钟前
escape谨慎使用
前端·javascript·vue.js
奶球不是球5 分钟前
elementplus组件中el-calendar组件自定义日期单元格内容及样式
javascript·css·css3
叠叠乐21 分钟前
robot_state_publisher 参数
java·前端·算法
Kiri霧21 分钟前
Range循环和切片
前端·后端·学习·golang
过期动态23 分钟前
JDBC高级篇:优化、封装与事务全流程指南
android·java·开发语言·数据库·python·mysql
WizLC24 分钟前
【Java】各种IO流知识详解
java·开发语言·后端·spring·intellij idea
小张快跑。31 分钟前
【Java企业级开发】(十一)企业级Web应用程序Servlet框架的使用(上)
java·前端·servlet
傻啦嘿哟33 分钟前
实战:用Splash搞定JavaScript密集型网页渲染
开发语言·javascript·ecmascript
Knight_AL36 分钟前
Java 线程池预热(Warm-up)实战:开启与不开启到底差多少?
java·开发语言
小白阿龙40 分钟前
Flex布局子元素无法垂直居中
前端