LoginSignup
1
1

More than 3 years have passed since last update.

Node.jsでローカルにある複数の画像をディレクトリを分けつつリサイズする

Posted at

ディレクトリ毎に分けた複数の画像を一度にリサイズするべく、スクリプトを書きました。
元の画像の縦横比が全て揃っており、リサイズする画像も元の画像の縦横比を保ったままにすることを前提としています。

環境

  • MacOS
  • Node.jsのバージョン・・・12.8.1
  • npmのバージョン・・・6.10.2

前提

以下がインストール済みであることを前提としています。

  • Node.js
  • npm(又はyarn)

ディレクトリ構造

├── node-extensions
│   └── sharp.js ← 実行するスクリプトファイル。
├── node_modules/
├── package.json
├── src
│   ├── images
│   │   ├── gallery
│   │   │   ├── l ← 元の画像を入れるディレクトリ。この下に年月毎のフォルダを作成。
│   │   │   └── s ← リサイズ後の画像を入れるディレクトリ。スクリプト実行後に生成。

パッケージのインストール・スクリプトの実行

必要なもの

  • sharp・・・画像のリサイズ
  • mkdirp・・・ディレクトリを生成

スクリプトを書く

sharp.js
const sharp = require('sharp');
const fs = require('fs');
const fsPromises = fs.promises;
const glob = require('glob');
const path = require('path');
const mkdirp = require('mkdirp');

const RESIZE_WIDTH = 600; // リサイズ後の画像の幅

const ORIGINAL_IMG_DIR = glob.sync('../src/images/gallery/l/*/'); // 元画像を格納しているディレクトリ
const IMG_DATE_DIR = ORIGINAL_IMG_DIR.map(imgDirPath => imgDirPath.split('/', 6)[5]); // 日付のディレクトリ
const RESIZED_IMG_PARENT_DIRNAME = '../src/images/gallery/s/'; // リサイズ後の画像を入れるディレクトリ名
const RESIZED_IMG_DIR_ARRAY = IMG_DATE_DIR.map((name) =>
  RESIZED_IMG_PARENT_DIRNAME + name
); // リサイズ後の画像を入れるディレクトリ


/**
 * 画像をリサイズしてリサイズ後のディレクトリに格納する
 * @param {string} imgPath リサイズ前の画像パス 
 * @param {string} outputFilePath リサイズ後の画像パス
 */
function createResizeImage(imgPath, outputFilePath) {
  sharp(imgPath)
  .resize(RESIZE_WIDTH)
  .toFile(outputFilePath, (err) => {
    if ( err ) console.error(err);
    return;
  });
}

/**
 * リサイズ後の画像を入れるディレクトリを生成
 */
RESIZED_IMG_DIR_ARRAY.forEach((pathName) => {
  mkdirp.sync(pathName, (err) => {
    if ( err ) console.error(err);
    return;
  });
});


ORIGINAL_IMG_DIR.forEach((dirName, i) => {
  const resolvedPath = path.resolve(dirName);  
  fsPromises.readdir(resolvedPath)
    .then((files) => {
      console.log(files);
      files.forEach((file) => {
        createResizeImage(resolvedPath + '/' + file, path.resolve(RESIZED_IMG_DIR_ARRAY[i]) + '/' + file);
      });
    })
    .catch((err) => {
      console.log(err.message);
    });
});

スクリプトを実行する

node-extensions のディレクトリまで移動して、以下を実行。

node sharp.js

src/images/gallery/l/ の下に 201912/ というディレクトリの中に画像ファイルを入れている場合。
スクリプト実行後に src/images/gallery/s/201912/ のディレクトリが生成されて、リサイズ後の同一ファイル名の画像が格納されます。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1