Closed Minglu-Huo closed 4 weeks 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.
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.
I hope this information helped. Please feel free to re-open with more details if further assistance is required.
@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.
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?