【问题标题】:Bulk Convert Entire Folder of Images with sharp使用锐利批量转换整个图像文件夹
【发布时间】:2021-07-27 20:57:18
【问题描述】:

我有一个项目,我需要将大量 .png 文件批量转换为 .jpgs,并对压缩质量进行一些控制。使用节点模块 sharp 就像对单个文件的魅力一样,例如:

const sharp = require("sharp");

sharp("input/82.png")
  .toFormat("jpeg")
  .jpeg({ quality: 70 })
  .toFile("output/82.jpg");

但我需要一次性转换数百个文件。我曾希望能够对文件使用一些通配符,例如:

sharp("input/*.png")
  .toFormat("jpeg")
  .jpeg({ quality: 70 })
  .toFile("output/*.jpg");

虽然这当然行不通,我也没有尝试遍历所有文件,或使用节点模块glob。感谢您在此处提供的任何指导。

【问题讨论】:

  • 您提到您尝试迭代文件失败。那些尝试是什么?如果您发布代码,将有可能帮助调试它。
  • 一个公平的要求,但是,因为我是个新手,而且尝试非常原始,所以它从来没有接近工作 - 不幸的是,没有什么可以调试的。

标签: node.js image-conversion sharp


【解决方案1】:

在另一位开发者的帮助下,结果比我预想的要复杂一些,需要使用节点模块glob

// example run : node sharp-convert.js ~/Projects/docs/public/images/output/new

const fs = require('fs');
const process = require('process');
const path = require('path');
const glob = require("glob")


const dir = process.argv[2];

const input_path = path.join(dir, '**', '*.png');
const output_path = path.join(dir, "min");

const sharp = require('sharp');

glob(input_path, function (err, files) {
  if (err != null) { throw err; }
  fs.mkdirSync(output_path, { recursive: true });
  files.forEach(function(inputFile) {
  sharp(inputFile)
    .jpeg({ mozjpeg: true, quality: 60, force: true })
    .toFile(path.join(output_path, path.basename(inputFile, path.extname(inputFile))+'.jpg'), (err, info) => {
      if(err === null){
          fs.unlink(inputFile, (err2) => {
              if (err2) throw err2;
              console.log('successfully compressed and deleted '+inputFile);
          });
      } else { throw err }
    });
  });
});

注意:此方法具有破坏性,会删除所有现有的 .png。请务必备份您的原件。

【讨论】:

    猜你喜欢
    • 2021-10-07
    • 2019-07-19
    • 2012-02-01
    • 2022-01-24
    • 2013-04-15
    • 1970-01-01
    • 2012-06-13
    • 1970-01-01
    • 2019-09-29
    相关资源
    最近更新 更多