lovell / sharp

High performance Node.js image processing, the fastest module to resize JPEG, PNG, WebP, AVIF and TIFF images. Uses the libvips library.
https://sharp.pixelplumbing.com
Apache License 2.0
28.86k stars 1.29k forks source link

if the image is a QR code or contains a QR code, the result is larger than the original image. #4173

Closed Minglu-Huo closed 4 weeks ago

Minglu-Huo commented 1 month ago

When I use Sharp to compress PNG images, I find that if the image is a QR code or contains a QR code, after I use sharp(file.buffer).png({ quality: 80 }).toBuffer() for compression, the result is larger than the original image. This is not the outcome I expected. What should I do to address this?

g

ayushmourya commented 1 month ago

For QR codes, avoid lossy compression as it can increase file size. Use lossless compression instead with Sharp: sharp(file.buffer).png({ compressionLevel: 9, adaptiveFiltering: true, palette: true }).toBuffer() This applies maximum lossless compression, adaptive filtering, and palette conversion, which is more suitable for QR codes. Always test the compressed images to ensure they remain scannable.

lovell commented 1 month ago

If you know your output PNG will contain only 2 possible pixel values then you can limit the palette to a relevant size:

const output = await sharp(input).png({ colours: 2 }).toBuffer();

This reduces the file size of the sample image provided from 11441 bytes to 5209 bytes.

https://sharp.pixelplumbing.com/api-output#png

lovell commented 4 weeks ago

I hope this information helped. Please feel free to re-open with more details if further assistance is required.

Minglu-Huo commented 2 weeks ago

@lovell Thank you very much for your help. I think I should first identify whether the image contains a QR code, and then use the configuration you provided to compress it.