你可以使用以下代码来实现:

const fs = require('fs');
const path = require('path');
const exec = require('child_process').exec;

// 设置源目录和目标目录
const fromDir = '/path/to/fromDir';
const destDir = '/path/to/destDir';

// 获取源目录中的所有文件
fs.readdir(fromDir, (err, files) => {
  if (err) {
    console.error('Error reading directory:', err);
    return;
  }

  // 过滤出所有的jpg和png文件
  const imageFiles = files.filter(file => {
    const ext = path.extname(file).toLowerCase();
    return ext === '.jpg' || ext === '.png';
  });

  // 压缩每个图片文件并写入目标目录
  imageFiles.forEach(file => {
    const inputFile = path.join(fromDir, file);
    const outputFile = path.join(destDir, file);

    // 使用imagemagick命令进行压缩
    const command = `convert ${inputFile} -resize 50% ${outputFile}`;

    exec(command, (error, stdout, stderr) => {
      if (error) {
        console.error(`Error compressing ${file}:`, error);
        return;
      }
      console.log(`Compressed ${file} successfully!`);
    });
  });
});

请确保已经安装了imagemagick命令行工具,并且在代码中正确地设置了源目录和目标目录的路径。代码会遍历源目录中的所有文件,过滤出扩展名为.jpg.png的文件,并使用imagemagick命令进行压缩,压缩后的文件会写入目标目录中

js 根据fromDir获取其中所有的jpg或者 png图片然后使用imagemagick压缩完成之后写入destDir

原文地址: https://www.cveoy.top/t/topic/i0zG 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录