LoginSignup
6
4

More than 3 years have passed since last update.

Node.jsで任意の画像からよさ気な部分を自動で切り取る

Last updated at Posted at 2019-09-18

任意の画像からよさ気な部分を自動で切り取るスクリプト・「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だけで画像処理をやれるのはいいですね。中のアルゴリズムは全然把握してないけど使う分には楽しそうです。

6
4
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
6
4