Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a thumbnail image in NodeJs using sharp library?

Tags:

node.js

npm

image

I am trying to find a suitable library for image processing,
Basically, I have a use-case for Resizing, Compressing and creating thumbnails of an image,
I found that sharp seems to be a popular node library choice for image processing,

I am able to do some basic operations like resizing an image but,
I couldn't find a way to create thumbnails or smaller sized quality images of the original one.
Can someone please point to the correct code for creating thumbnails and smaller resolution images using the sharp library?

Sample working code:

const sharp = require('sharp');

let test = async () => {

    await sharp('/pathToImage/test.jpg')
    .resize({
        fit: sharp.fit.outside
    })
    .sharpen()
    .toFile('fitOutside.jpg')
    .then(info => { 
        console.log(info);
    })
    .catch(err => {
        console.log(err);
    });

};

test();

Reference -
http://sharp.pixelplumbing.com/en/stable/api-resize/
https://sharp.pixelplumbing.com/en/stable/api-resize/#examples_2

like image 704
Ani Avatar asked May 12 '26 18:05

Ani


1 Answers

If you give both width and height, sharp will usually need to either add or remove pixels on one axis. You can control what it does with the fit parameter:

http://sharp.pixelplumbing.com/en/stable/api-resize/

The default is centre, it sounds like you'd prefer outside.

like image 80
jcupitt Avatar answered May 15 '26 08:05

jcupitt