Top Related Projects
GIF encoder based on libimagequant (pngquant). Squeezes maximum possible quality from the awful GIF format.
Zopfli Compression Algorithm is a compression library programmed in C to perform very good, but slow, deflate or zlib compression.
Improved JPEG encoder.
Perceptual JPEG encoder
High performance Node.js image processing, the fastest module to resize JPEG, PNG, WebP, AVIF and TIFF images. Uses the libvips library.
Quick Overview
pngquant is a command-line utility and a library for lossy compression of PNG images. It significantly reduces file sizes by converting images to a more efficient 8-bit PNG format with alpha channel. The tool uses a quantization algorithm to produce high-quality results while maintaining a small file size.
Pros
- Achieves significant file size reduction (often 60-80%) while maintaining visual quality
- Supports both command-line usage and integration as a library
- Fast processing speed, especially with the latest optimizations
- Preserves full alpha transparency in PNG images
Cons
- Lossy compression may not be suitable for all use cases
- Limited to PNG format only
- May introduce slight visual artifacts in some images
- Requires careful parameter tuning for optimal results in certain scenarios
Code Examples
- Basic usage as a library:
use pngquant::{Image, Result};
fn compress_image(input_path: &str, output_path: &str) -> Result<()> {
let mut img = Image::new_from_file(input_path)?;
img.quantize(256)?;
img.write_png(output_path)
}
- Customizing compression settings:
use pngquant::{Image, Attributes, Result};
fn compress_with_options(input_path: &str, output_path: &str) -> Result<()> {
let mut img = Image::new_from_file(input_path)?;
let mut attributes = Attributes::new();
attributes.set_speed(1); // Highest quality, slowest speed
attributes.set_quality(80, 99); // Quality range
img.quantize_with_attributes(&attributes)?;
img.write_png(output_path)
}
- Processing an image in memory:
use pngquant::{Image, rgba_to_u8_slice, Result};
fn compress_in_memory(rgba_data: &[u8], width: u32, height: u32) -> Result<Vec<u8>> {
let mut img = Image::new_from_rgba(rgba_data, width, height)?;
img.quantize(256)?;
let (output_data, _) = img.get_output_image()?;
Ok(rgba_to_u8_slice(&output_data))
}
Getting Started
To use pngquant as a library in your Rust project, add the following to your Cargo.toml
:
[dependencies]
pngquant = "3.0"
Then, in your Rust code:
use pngquant::{Image, Result};
fn main() -> Result<()> {
let mut img = Image::new_from_file("input.png")?;
img.quantize(256)?;
img.write_png("output.png")
}
This example reads an input PNG file, quantizes it to 256 colors, and writes the compressed result to a new file.
Competitor Comparisons
GIF encoder based on libimagequant (pngquant). Squeezes maximum possible quality from the awful GIF format.
Pros of gifski
- Specializes in high-quality GIF encoding from video sources
- Offers a command-line interface and a Rust library for integration
- Utilizes advanced algorithms for optimal frame selection and color quantization
Cons of gifski
- Limited to GIF format, while pngquant focuses on PNG optimization
- May have longer processing times due to its focus on quality over speed
- Lacks some of the advanced compression features found in pngquant
Code Comparison
gifski:
let mut encoder = Encoder::new(output_file, width, height, repeat)?;
encoder.set_quality(quality);
encoder.set_fast(fast);
encoder.write_frame(&frame, delay_ms)?;
pngquant:
pngquant_image *image = pngquant_image_create_from_file(input_path);
pngquant_set_quality(image, min_quality, max_quality);
pngquant_set_speed(image, speed);
pngquant_write(image, output_path);
Key Differences
- gifski focuses on creating high-quality GIFs from video sources, while pngquant specializes in PNG optimization
- pngquant offers more granular control over compression settings
- gifski provides a Rust library, whereas pngquant is primarily C-based
- Both tools offer command-line interfaces, but with different optimization targets
Zopfli Compression Algorithm is a compression library programmed in C to perform very good, but slow, deflate or zlib compression.
Pros of Zopfli
- Achieves higher compression ratios for PNG images
- Supports multiple compression algorithms (DEFLATE, GZIP, ZLIB)
- Developed and maintained by Google, ensuring long-term support
Cons of Zopfli
- Significantly slower compression speed compared to Pngquant
- Limited focus on PNG optimization, as it's a general-purpose compression library
- Lacks advanced features like color palette optimization
Code Comparison
Zopfli (C++):
ZopfliOptions options;
ZopfliInitOptions(&options);
unsigned char* out = 0;
size_t outsize = 0;
ZopfliCompress(&options, ZopfliFormat::ZOPFLI_FORMAT_GZIP,
in, insize, &out, &outsize);
Pngquant (C):
liq_attr *attr = liq_attr_create();
liq_image *image = liq_image_create_rgba(attr, raw_rgba_pixels, width, height, 0);
liq_result *res = liq_quantize_image(attr, image);
liq_write_remapped_image(res, image, output_pixels, output_pixels_size);
Both libraries offer efficient image compression, but Zopfli focuses on achieving higher compression ratios at the cost of speed, while Pngquant specializes in fast, high-quality PNG optimization with color palette reduction. Zopfli is more versatile for general compression tasks, whereas Pngquant excels in PNG-specific optimizations.
Improved JPEG encoder.
Pros of mozjpeg
- Specializes in JPEG compression, offering superior JPEG optimization
- Provides both lossy and lossless JPEG compression options
- Includes advanced features like trellis quantization and progressive scan optimization
Cons of mozjpeg
- Limited to JPEG format, while pngquant handles PNG files
- May have slower compression speeds compared to pngquant for PNG files
- Requires more complex integration due to its C-based implementation
Code Comparison
mozjpeg:
cinfo.optimize_coding = TRUE;
jpeg_set_quality(&cinfo, quality, TRUE);
jpeg_simple_progression(&cinfo);
pngquant:
let mut liq = Attributes::new();
liq.set_quality(0, 100);
let image = liq.new_image(&rgba, width, height, 0.0)?;
Summary
mozjpeg excels in JPEG compression, offering advanced optimization techniques for this specific format. It provides both lossy and lossless options, making it versatile for JPEG handling. However, it's limited to JPEG files, unlike pngquant which focuses on PNG optimization. mozjpeg may have slower compression speeds for certain use cases and can be more complex to integrate due to its C implementation. pngquant, on the other hand, is specialized for PNG files and offers a simpler Rust-based integration. The choice between these tools depends on the specific image format requirements and the balance between compression quality and processing speed needed for a project.
Perceptual JPEG encoder
Pros of Guetzli
- Achieves higher compression ratios for JPEG images
- Produces visually superior results with fewer artifacts
- Developed and maintained by Google, ensuring ongoing support
Cons of Guetzli
- Significantly slower compression process compared to pngquant
- Limited to JPEG format, while pngquant works with PNG images
- Higher memory usage during compression
Code Comparison
pngquant:
void pngquant_image(liq_attr *options, liq_image *input_image, png24_image *output_image)
{
liq_result *quantization_result;
liq_quantize_image(options, input_image, &quantization_result);
// ... (further processing)
}
Guetzli:
bool ProcessJpegData(const JPEGData& jpg_in, const guetzli::Params& params,
std::string* jpg_out, double* distmap, bool verbose) {
// ... (compression logic)
return true;
}
Summary
While Guetzli excels in JPEG compression quality and visual results, pngquant offers faster processing for PNG images. Guetzli's higher compression ratios come at the cost of longer processing times and increased memory usage. pngquant provides a more versatile solution for PNG optimization, while Guetzli focuses solely on JPEG compression. The choice between the two depends on the specific image format and the balance between compression quality and processing speed required for the project.
High performance Node.js image processing, the fastest module to resize JPEG, PNG, WebP, AVIF and TIFF images. Uses the libvips library.
Pros of sharp
- Supports multiple image formats (JPEG, PNG, WebP, AVIF, TIFF)
- Provides a wide range of image processing operations (resize, crop, rotate, etc.)
- High-performance processing using libvips
Cons of sharp
- Larger package size due to comprehensive feature set
- More complex setup and installation process
- Steeper learning curve for basic operations
Code comparison
sharp:
import sharp from 'sharp';
sharp('input.png')
.resize(300, 200)
.toFile('output.png');
pngquant:
import { execFile } from 'child_process';
import pngquant from 'pngquant-bin';
execFile(pngquant, ['-o', 'output.png', 'input.png']);
Summary
sharp is a versatile image processing library that supports multiple formats and operations, making it suitable for complex image manipulation tasks. It offers high performance but comes with a larger package size and steeper learning curve.
pngquant, on the other hand, is focused specifically on PNG optimization. It's lightweight, easy to use, and excels at reducing PNG file sizes while maintaining quality. However, it lacks the broader feature set of sharp and is limited to PNG format only.
Choose sharp for comprehensive image processing needs across various formats, and pngquant for efficient PNG optimization in simpler workflows.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
pngquant 3
pngquant is a PNG compressor that significantly reduces file sizes by converting images to a more efficient 8-bit PNG format with alpha channel (often 60-80% smaller than 24/32-bit PNG files). Compressed images are fully standards-compliant and are supported by all web browsers and operating systems.
This is the official pngquant
repository. The compression engine is also available as an embeddable library.
Usage
- batch conversion of multiple files:
pngquant *.png
- Unix-style stdin/stdout chaining:
⦠| pngquant - | â¦
To further reduce file size, try oxipng, ImageOptim, or zopflipng.
Features
- High-quality palette generation
- advanced quantization algorithm with support for gamma correction and premultiplied alpha
- unique dithering algorithm that does not add unnecessary noise to the image
- Configurable quality level
- automatically finds required number of colors and can skip images which can't be converted with the desired quality
- Fast, modern code
- based on a portable libimagequant library
- C99 with no workarounds for legacy systems or compilers (apart from Visual Studio)
- multicore support (via OpenMP) and Intel SSE optimizations
Options
See pngquant -h
for full list.
--quality min-max
min
and max
are numbers in range 0 (worst) to 100 (perfect), similar to JPEG. pngquant will use the least amount of colors required to meet or exceed the max
quality. If conversion results in quality below the min
quality the image won't be saved (if outputting to stdin, 24-bit original will be output) and pngquant will exit with status code 99.
pngquant --quality=65-80 image.png
--ext new.png
Set custom extension (suffix) for output filename. By default -or8.png
or -fs8.png
is used. If you use --ext=.png --force
options pngquant will overwrite input files in place (use with caution).
-o out.png
or --output out.png
Writes converted file to the given path. When this option is used only single input file is allowed.
--skip-if-larger
Don't write converted files if the conversion isn't worth it.
--speed N
Speed/quality trade-off from 1 (slowest, highest quality, smallest files) to 11 (fastest, less consistent quality, light comperssion). The default is 4. It's recommended to keep the default, unless you need to generate images in real time (e.g. map tiles). Higher speeds are fine with 256 colors, but don't handle lower number of colors well.
--nofs
Disables Floyd-Steinberg dithering.
--floyd=0.5
Controls level of dithering (0 = none, 1 = full). Note that the =
character is required.
--posterize bits
Reduce precision of the palette by number of bits. Use when the image will be displayed on low-depth screens (e.g. 16-bit displays or compressed textures in ARGB444 format).
--strip
Don't copy optional PNG chunks. Metadata is always removed on Mac (when using Cocoa reader).
See man page (man pngquant
) for the full list of options.
License
pngquant is dual-licensed:
-
Under GPL v3 or later with an additional copyright notice that must be kept for the older parts of the code.
-
Or a commercial license for use in non-GPL software (e.g. closed-source or App Store distribution). You can get the license via Super Source. Email kornel@pngquant.org if you have any questions.
Top Related Projects
GIF encoder based on libimagequant (pngquant). Squeezes maximum possible quality from the awful GIF format.
Zopfli Compression Algorithm is a compression library programmed in C to perform very good, but slow, deflate or zlib compression.
Improved JPEG encoder.
Perceptual JPEG encoder
High performance Node.js image processing, the fastest module to resize JPEG, PNG, WebP, AVIF and TIFF images. Uses the libvips library.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot