25

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 ?

4
  • 2
    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. Commented Jul 11, 2018 at 18:03
  • yes that's a solution but i want to do same instead of checks Commented Jul 11, 2018 at 18:12
  • I check but not find...that's why I post question Commented Jul 11, 2018 at 18:48
  • different formats require different method decoding and encoding, so checking extension is a good idea. Commented Sep 25, 2018 at 15:58

3 Answers 3

12

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)

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

7

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.