Sharp とは
Sharp は、画像編集するためのパッケージです。
インストール
npm i sharp
Sharp は、画像編集するためのパッケージです。
npm i sharp
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);
});
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
}
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')
}
})