Compress image using sharp in node.js

Haseeb Ahmad picture Haseeb Ahmad · Jul 11, 2018 · Viewed 12.5k times · Source

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 ?

Answer

sbay picture sbay · Aug 16, 2019

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