20

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 ?

Haseeb Ahmad
  • 7,914
  • 12
  • 55
  • 133

3 Answers3

9

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.pixelplumbing.com/api-output#jpeg

nameless
  • 5
  • 3
sbay
  • 435
  • 1
  • 7
  • 20
5

PNG is also quality, but as it is a lossless format, this is set to 100 by default. Where-as JPG is set to 80 by default.

By reducing the quality for PNG, it will enable the palette mode which will reduce the number of colours captured in the encoding. This will provide some good size reduction for the file.

compression is just zlib / zip compression, haven't found it does much TBH.

All in the docs: https://sharp.pixelplumbing.com/api-output#png

// this will disable loss-less mode, and reduce the colour accuracy to 90%
// it will also enable the palette
sharp('_4_.jpg')
 .resize(1000)
 .png({quality: 90})

sonjz
  • 4,870
  • 3
  • 42
  • 60
5

You can grab file format with metadata method and select according optimisation method for it:

const image = sharp('_4_.jpg')
const meta = await image.metadata()
const { format } = meta

const config = {
  jpeg: { quality: 80 },
  webp: { quality: 80 },
  png: {compressionLevel: 8},
}

await image[format](config[format])
  .resize(1000)

Eugene Blinn
  • 303
  • 2
  • 6
Kuzzy
  • 562
  • 1
  • 9
  • 24