I
I
Ivan Ivanovich2021-02-16 18:31:34
Node.js
Ivan Ivanovich, 2021-02-16 18:31:34

How to efficiently compress images in nodejs?

Good day.

The task is to compress images and then save them.
Googling, I found the best option - the sharp package .

But here a problem arose.

My code:

sharp()
    .withMetadata()
    .jpeg({ quality: 50, force: false })
    .png({ compressionLevel: 9, force: false })
    .webp({ quality: 50, force: false })
    .toBuffer();


Everything works correctly with jpeg and webp, but png doesn't want to compress at all. And sometimes even vice versa, after compression they become larger in size.

Tried with different options, no result. Set quality: 50 - doesn't work, including with palette set to true. But it is worth noting that I somehow set the adaptiveFiltering option to true, the images began to weigh a few kilobytes less.

As I understand it, in general, nodejs is not designed for tasks such as compressing images, but still, what could be the reason that pngs are not compressed?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
WbICHA, 2021-02-16
@IwanQ

Sir, you are doing something crazy.
First, the image is converted to zip with 50% quality, then to png using lossless compression, and finally converted to webp again with 50% quality.
After all this, I'm more than sure that you save everything with the original file extension, in other words, convert the resulting webp to zipeg / png. And given that PNG is incompressible, how do you expect to get a PNG with a much smaller volume?

sharp()
    .withMetadata()
    .jpeg({ quality: 50 })
    .toFile(path.join(__dirname, `some/path/${filename}.jpg`));

PS: I recommend reading the documentation: https://sharp.pixelplumbing.com/api-output#jpeg

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question