LoginSignup
0
0

任意のサイズのダミー画像を作成するCLIツールを作ろう

Last updated at Posted at 2024-05-01

はじめに

webサービス開発をしていると、「仮の画像を一旦入れておきたい」みたいなシーンありますよね。

例えばweb上では、株式会社ソフテル様がplacehold.jpというツールを提供されています。

似たようなことがローカル環境でもできたら開発が便利になるのではと思いました。

結論

作ったのでよかったら使ってみてください。
https://www.npmjs.com/package/placeholder-craft-cli

使い方

以下、Node.jsがインストールされていることを前提としています。

インストール

npm install -g placeholder-craft-cli

画像を生成

phcraft --width 500 --height 500 --filename hoge.png

現時点で以下のオプションに対応しています。

  -w, --width      幅(必須)
  -h, --height     高さ(必須)
  -b, --bgColor    背景色(デフォルト: "grey")
  -t, --textColor  文字色(デフォルト: "white")
  -f, --filename   ファイル名(デフォルト: "placeholder.png")

実装の話

画像生成

node-canvas という、webのCanvas APIとの互換を目指したNode.jsで使えるパッケージを利用しています。

import { createCanvas } from "canvas";

// 縦横を指定してキャンバスを生成
const canvas = createCanvas(width, height);
// 二次元の描画コンテキストを取得
const ctx = canvas.getContext("2d");
// 好きなように描画していく
ctx.fillStyle = bgColor;
ctx.fillRect(0, 0, width, height);
ctx.fillStyle = textColor;

最後に、ファイル出力してあげればOKです。

const buffer = canvas.toBuffer("image/png");
	fs.writeFileSync(filename, buffer);

オプション引数

コマンドライン引数の受け取りをyargsを使って実現します。

import yargs from "yargs";

const argv = yargs
	.option("width", {
		alias: "w",
		describe: "The width of the image",
		type: "number",
		demandOption: true,
	})
     // optionは複数定義可能
     .option("hoge", {
		// 略
	})
	.help() // --helpオプションに対応
	.parseSync() as PlaceholderImageOptions; // オブジェクトにパース

createPlaceholderImage(argv);

コード

以下に全文が載っています。
https://github.com/macaroni10y/placeholder-craft-cli

さいごに

何かご質問、ご指摘などありましたら是非お願いいたします。

0
0
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
0
0