Files
Shell-Scripts/all-png-to-webp.js
T

84 lines
2.1 KiB
JavaScript

#!/usr/bin/env node
const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');
const AUTHOR = '奇趣保罗';
function commandExists(command) {
try {
const check =
process.platform === 'win32' ? `where ${command}` : `command -v ${command}`;
execSync(check, { stdio: 'ignore' });
return true;
} catch {
return false;
}
}
function quotePath(filePath) {
return `"${filePath.replace(/"/g, '\\"')}"`;
}
function syncFileTimes(sourcePath, targetPath) {
const { atime, mtime } = fs.statSync(sourcePath);
fs.utimesSync(targetPath, atime, mtime);
}
function main() {
if (!commandExists('magick')) {
console.error('错误: 未找到 ImageMagick,请先安装 ImageMagick');
process.exit(1);
}
if (!commandExists('exiftool')) {
console.error('错误: 未找到 ExifTool,请先安装 ExifTool');
process.exit(1);
}
const workDir = process.cwd();
const pngFiles = fs
.readdirSync(workDir)
.filter((file) => {
const fullPath = path.join(workDir, file);
return (
fs.statSync(fullPath).isFile() && path.extname(file).toLowerCase() === '.png'
);
});
if (pngFiles.length === 0) {
console.log('当前目录下没有 PNG 文件');
return;
}
for (const pngFile of pngFiles) {
const pngPath = path.join(workDir, pngFile);
const filename = path.basename(pngFile, path.extname(pngFile));
const webpPath = path.join(workDir, `${filename}.webp`);
if (fs.existsSync(webpPath)) {
console.log(`跳过: ${filename}.webp 已存在`);
continue;
}
console.log(`正在转换: ${pngFile} -> ${filename}.webp`);
execSync(`magick ${quotePath(pngPath)} ${quotePath(webpPath)}`, {
stdio: 'inherit',
});
console.log(`正在写入作者信息到: ${filename}.webp`);
execSync(
`exiftool -overwrite_original -Author=${quotePath(AUTHOR)} ${quotePath(webpPath)}`,
{ stdio: 'inherit' }
);
console.log(`正在同步创建日期: ${filename}.webp <- ${pngFile}`);
syncFileTimes(pngPath, webpPath);
}
console.log('所有文件处理完成!');
}
main();