Compress image using sharp in node.js
Asked Answered
S

3

23

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 ?

Smalt answered 11/7, 2018 at 17:57 Comment(4)
Why don't you just check the extension and act accordingly? If you want a more precise detection you can read the first bytes of the image, but I don't think that is necessary.Wrangle
yes that's a solution but i want to do same instead of checksSmalt
I check but not find...that's why I post questionSmalt
different formats require different method decoding and encoding, so checking extension is a good idea.Selfabsorption
P
10

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)

Procreant answered 7/10, 2021 at 12:28 Comment(0)
S
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

Schurman answered 16/8, 2019 at 21:46 Comment(0)
L
6

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})

Lansing answered 20/7, 2021 at 21:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.