任意の画像からよさ気な部分を自動で切り取るスクリプト・「smartcrop.js」
の記事にあるsmartcropのNode.js版を試してみました。
smartcrop-sharpというライブラリを使います。
環境
- Node.js 12.10.0
$ npm i sharp smartcrop-sharp
コード
コードもシンプルです。
app.js
'use strict';
const fs = require('fs');
const sharp = require('sharp');
const smartcrop = require('smartcrop-sharp');
const main = (input, output, width=500, height=500) => {
const body = fs.readFileSync(input);
return smartcrop.crop(body, { width: width, height: height })
.then(result => {
const crop = result.topCrop;
return sharp(body)
.extract({ width: crop.width, height: crop.height, left: crop.x, top: crop.y })
.resize(width, height)
.toFile(output);
});
}
//実行
main('./input.png', './output.png').then();
結果
こんな感じになりました。画像はtwilioのロゴを真似て書いたやつです。
↓
余白をいい感じにクロップしてくれていて、結構よさげな印象です。
Node.jsだけで画像処理をやれるのはいいですね。中のアルゴリズムは全然把握してないけど使う分には楽しそうです。