Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How do I optimize an image (Loseless compression) to reduce the file size of an image? #4342

Closed
trymeouteh opened this issue Feb 28, 2025 · 3 comments
Labels

Comments

@trymeouteh
Copy link

Question about an existing feature

What are you trying to achieve?

What is the bet way to optimize (compressing an image using loseless compression) to reduce the file size of an image. I would like to know how to do this for JPEG images, PNG images, GIF images and WEBP images.

When you searched for similar issues, what did you find that might be related?

By going through the documentation and stackoverflow anwsers.

Please provide a minimal, standalone code sample, without other dependencies, that demonstrates this question

This is what I came up with so far and does work well for JPEG, PNG and WEBP images. However I cannot seem to get much optimization on GIF images (perhaps my GIF image is already optimized to its fullest)

import sharp from 'sharp';

await sharp('input.jpg').jpeg({ mozjpeg: true }).toFile('output.jpg');
await sharp('input.png').png({ compressionLevel: 9, quality: 100 }).toFile('output.png');
await sharp('input.gif').toFile('output.gif');
await sharp('input.webp').webp({ loseless: true, quality: 80 }).toFile('output.webp');

Please provide sample image(s) that help explain this question

Download link for each image example...
https://ufile.io/f/67ij3

@lovell
Copy link
Owner

lovell commented Feb 28, 2025

If you need to use lossless compression then JPEG, GIF and palette-based PNG are off-limits as they are lossy. That leaves you with full colour PNG and lossless (rather than "loseless") WebP. Remove the quality settings from your examples and that's probably the best you can do.

@trymeouteh
Copy link
Author

Remove the quality settings from your examples and that's probably the best you can do.

Are the quality settings used for the PNG and WEBP images above going to be noticeable to the naked eye?

@lovell
Copy link
Owner

lovell commented Mar 18, 2025

You'll need to experiment with your own images to determine subjective measures like this. Perhaps try tooling such as https://github.com/cloudinary/ssimulacra2 to help.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants