画像の圧縮方法を調べていたらlibsquoosh
というのを知った
web.devで記事になっていた
そもそもsquoosh.appというのがあり、これがブラウザで画像を圧縮することができるPWAということ(オフラインでも動く)、そしてChrome DevSummit 2020で Squoosh v2
がアナウンスされ注目を集めているらしい
libsquoosh
はそれをブラウザからではなく、複数の画像処理を一度に実行できるようにNodeモジュール化したもの
開発者がそれをWebpack、Rollup、その他のビルドツールに統合し、Web用に最適化するのを容易にすることを目標にしているみたい
試してみた
ドキュメントに書かれているスニペットを参考に試してみた
$ npm install @squoosh/lib
index.js
import { ImagePool } from "@squoosh/lib"; import fs from "fs"; // libSquoosh uses a worker-pool under the hood // to parallelize all image processing. const imagePool = new ImagePool(); // Accepts both file paths and Buffers/TypedArrays. const image = imagePool.ingestImage("./img/sample.jpg"); // Optional. // await image.preprocess({ // resize: { // enabled: true, // width: 128, // }, // }); await image.encode({ // All codecs are initialized with default values // that can be individually overwritten. mozjpeg: { quality: 10, }, avif: { cqLevel: 10, }, jxl: {}, }); const { extension: extension1, binary: binary1 } = await image.encodedWith.mozjpeg; await fs.writeFile(`output.${extension1}`, binary1, (err) => { if (err) throw err; console.log('正常に書き込みが完了しました1'); }); const { extension: extension2, binary: binary2 } = await image.encodedWith.avif; await fs.writeFile(`output.${extension2}`, binary2, (err) => { if (err) throw err; console.log('正常に書き込みが完了しました2'); }); // ... same for other encoders ... await imagePool.close();
もっと綺麗になりそうだけど圧縮することができた
ただ、READMEにあるように、まだ実験的であり最速な圧縮ツールを目指しているわけではない(ちょっと遅い気がする)
いまのところ使う予定はないが、これがどう進展していくのかウォッチしていきたい