はじめに
画像をトリミングしたいという場面あり、それをnpm packageのsharpを使って実装したのでその方法をこの記事にまとめます。
shrapとは
Node.jsのmoduleで、大雑把に言うと画像形式の変換や画像の整形ができます。
The typical use case for this high speed Node.js module is to convert large images in common formats to smaller, web-friendly JPEG, PNG, WebP and AVIF images of varying dimensions.
引用:「sharp」
shrapを使って画像をトリミングする方法
画像をトリミングするにはresize
関数を使用します。resize
関数にfit引数を指定しない場合はデフォルトでfil:cover
が指定されます。このcoverはアスペクト比は保持して(画像が引き伸ばされたりしない)、指定されたwidthとheightからはみ出る部分はトリミングします。
cover: (default) Preserving aspect ratio, ensure the image covers both provided dimensions by cropping/clipping to fit.
引用:「Resizing images」
トリミングをする際の範囲の基準ですが、デフォルトではcenterが指定されています。なので上下左右、中央中心にwidthとheightからはみ出た部分がトリミングされます。
以下のコードはinput.jpgの画像をwidth:720
,height:340
の比率に合わせて、中央中心にトリミングするコードになります。
const sharp = require("sharp");
sharp("input.jpg")
.resize({
width: 720,
height: 340,
})
.toFile("output.jpg", (err, info) => {
if (err) {
console.error(err);
}
console.log(info);
});
参考文献: