批量处理图片

111 阅读1分钟

将文件夹A里面的照片剪切放到文件夹B,并且以照片拍摄时间为文件夹的名称

const fs = require('fs');
const path = require('path');

const folderA = 'path/to/folderA'; // 替换为文件夹A的路径
const folderB = 'path/to/folderB'; // 替换为文件夹B的路径

// 获取文件夹A中的所有文件
fs.readdir(folderA, (err, files) => {
  if (err) {
    console.error('无法读取文件夹A:', err);
    return;
  }

  // 遍历文件夹A中的文件
  files.forEach((file) => {
    const filePath = path.join(folderA, file);

    // 检查文件是否为图片(png或jpg)
    if (/\.(png|jpg)$/i.test(file)) {
      const fileDate = new Date(fs.statSync(filePath).mtime);
      const year = fileDate.getFullYear();
      const month = String(fileDate.getMonth() + 1).padStart(2, '0');
      const day = String(fileDate.getDate()).padStart(2, '0');

      const destinationFolder = path.join(folderB, `${year}-${month}-${day}`);
      const newFilePath = path.join(destinationFolder, file);

      // 创建目标文件夹(如果不存在)
      if (!fs.existsSync(destinationFolder)) {
        fs.mkdirSync(destinationFolder);
      }

      // 剪切文件到目标文件夹
      fs.rename(filePath, newFilePath, (err) => {
        if (err) {
          console.error(`无法剪切文件 ${file} 到目标文件夹:`, err);
        } else {
          console.log(`已剪切文件 ${file} 到目标文件夹`);
        }
      });
    }
  });
});