Sharp - Node.js

Sharp とは

Sharp は、画像編集するためのパッケージです。

インストール

npm i sharp

画像をリサイズして保存する

script.js

const sharp = require('sharp');
const image = sharp('./sample.jpg');
const width = 200;
const height = 100;

image.resize(width, height).toFile('new.jpg')
.then(info => {
  console.log(info);
})
.catch(error => {
  console.log(error);
});

メタデータを取得する

script.js

const sharp = require('sharp');
const image = sharp('./sample.jpg');
image.metadata()
  .then((metadata) => {
    console.log(metadata);
  });

結果

{
  format: 'jpeg',
  width: 1280,
  height: 849,
  space: 'srgb',
  channels: 3,
  depth: 'uchar',
  density: 72,
  chromaSubsampling: '4:2:0',
  isProgressive: false,
  hasProfile: false,
  hasAlpha: false
}

画像形式を変換する

  • jpg
  • jpeg
  • png
  • webp
  • tiff
  • heic
  • heif
  • raw

script.js

const sharp = require('sharp');
const image = sharp('./sample.jpg');

image.toFormat('png').toFile('new.png')
.then(info => {
  console.log(info);
})
.catch(error => {
  console.log(error);
});

画像サイズが大きい場合にリサイズする

画像の横幅が800pxより大きい場合、リサイズして保存するには以下のようにします。

const sharp = require('sharp');
const image = sharp('resize_before.jpg');

image.metadata().then(function(metadata) {
  if(metadata.width > 800){
    image.resize(400, null).toFile('resize_after.png')
  } else {
    image.toFile('resize_after.png')
  }
})