Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compress image using sharp in node.js

I want to resize and compress images using sharp in node.js

In sharp for jpeg there is separate compression and for webp there is separate and for png there is separate.

WEBP

sharp('a.jpg')
.resize(1000)
.webp({quality: 80})

JPEG

sharp('_4_.jpg')
 .resize(1000)
 .jpeg({quality: 80})

PNG

sharp('_4_.jpg')
 .resize(1000)
 .png({compressionLevel: 8})

Basically I want to compress and resize image without checking in which format they.

Is there anything for that in sharp ?

like image 957
Haseeb Ahmad Avatar asked Jul 11 '18 17:07

Haseeb Ahmad


People also ask

How do I reduce the size of an image in node JS?

NodeJS – Resize() is an inbuilt function that is used to resize the images to the desired size. We can use resize to set the height and width using a 2-pass bilinear algorithm. It can resize an image into any size as declared by the user. We can take input from the user or resize it into fixed Width*Height size.

What is sharp in node JS?

sharp is a popular Node. js image processing library that supports various image file formats, such as JPEG, PNG, GIF, WebP, AVIF, SVG and TIFF. In this tutorial, you'll use sharp to read an image and extract its metadata, resize, change an image format, and compress an image.

How do you decode a binary buffer to an image in node JS?

let binary = Buffer. from(data); //or Buffer. from(data, 'binary') let imgData = new Blob(binary. buffer, { type: 'application/octet-binary' }); let link = URL.


1 Answers

If you want the output format to match the input format, you should look at force option.

sharp(input)
  .jpeg({ progressive: true, force: false })
  .png({ progressive: true, force: false })
  ...

GIF output is not supported, so GIF input will become PNG output by default.

Additional reference: https://sharp.readthedocs.io/en/v0.17.0/api-output/#jpeg

like image 153
sbay Avatar answered Sep 29 '22 02:09

sbay