3
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

TinyPNGのAPIクライアントtinifyの使い方 [画像サイズの最適化]

Posted at

webサービスに画像サイズの最適化でよくお世話になるのがTinyPNG です。
ただ大量に画像ファイルがある時、いちいちサイトでアップロード、ダウンロードは大変ですよね。
TinyPNGをAPI経由で利用するためのnode_moduleがあったので紹介します。
(API経由での最適化は月500ファイルと制限はあります。)

プロジェクトの作成とtinifyの追加

まず作業ディレクトリの作成と、tinifyの追加を行います。

$ mkdir tinify-demo
$ cd tinify-demo
$ mkdir src dest
$ npm init -y 
$ yarn add -D tinify 

TinyPNGのAPIキーの取得

TinyPNGのAPI-clientの利用にはAPIキーが必要です。
https://tinypng.com/developers
より、メールアドレスの登録をすれば取得できます。

スクリーンショット 2019-04-01 7.38.05.png

index.jsの作成

実際の処理を行うindex.jsを書いていきます。
tinifyの最適化は以下数行のコマンドだけで利用できます。

const tinify = require("tinify");
tinify.key = "APIキー";
 
tinify.fromFile("対象ファイルのパス").toFile("出力ファイルのパス");

今回はsrc以下の画像すべてを圧縮対象とするので、node.jsのfsを使ってファイルを取得し、ループで回すようにしました。

$ vi index.js
index.js
const fs = require('fs');
const tinify = require('tinify');
tinify.key = 'TiniyPNGのAPIキー';

const srcDir = './src/';
const destDir = './dest/';
const targetFileType = /.*\.(png|PNG|jpeg|jpg|JPG|JPEG)$/;

const optimizeImage = async function (file) {
  const srcFile = srcDir + file;
  const destFile = destDir + file;

  // 最適化処理
  await tinify.fromFile(srcFile).toFile(destFile);

  // log
  console.log(`${file}  => ${Math.round(
      fs.statSync(destFile).size / fs.statSync(srcFile).size * 100)} %`);
};

fs.readdir(srcDir, (err, files) => {
  // 対象のファイルに対して最適化を実行
  files.filter(file => file.match(targetFileType)).forEach(file => {
    optimizeImage(file)
  })
});

あとは、node.jsでindex.jsを起動すればOKです。

$ node index.js
sample1.png  => 23 %
sample2.png  => 26 %
sample3.jpg  => 77 %
3
6
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
3
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?