Optimize Images Using Dynamic Color Quantization

Color quantization reduces the number of colors in an image while maintaining its overall visual construction. Depending on the file type, this can dramatically reduce the file size of the image. TinyPNG and other similar applications use color quantization to reduce image file sizes. Color quantization can also be used to produce artistic effects.

With imgix, you have the ability to perform color quantization operations on demand by merely changing a URL parameter. Let's see how it works for both optimization and effects.

mark-align=middle%2Ccenter&mark=https%3A%2F%2Fassets.imgix.net%2Fpresskit%2Fimgix-presskit.pdf%3Fw%3D160%26fm%3Dpng%26page%3D2&q=75&fm=png8&fit=crop&colorquant=9

Basic Usage

To use color quantization, set the colorquant parameter in your imgix URL. It accepts a value between 2 and 256. This operation is one of the last in the imgix order of operations, and will be applied after other image adjustments and compositing operations.

colorquant=16
colorquant=3

Using colorquant for Optimization

When considering color quantization for compression, you will see the biggest benefits when trying to shed some kilobytes from graphic elements, icons, or animations.

Used in conjunction with fm=png8, you can maintain a sharp and pixel-perfect graphic while reducing its file size by as much as 60%. The following example shows the same transparent PNG processed using colorquant and fm=png8. The original in this example is a 1200×900 lossless transparent PNG graphic exported originally from Adobe Illustrator’s “Save for Web” dialog.

Original: 83.15kB
?colorquant=28: 62.58kB
?fm=png8: 28.47kB
?fm=png8&colorquant=24: 18.69kB

While setting fm=png8 causes a great reduction alone, you can see that limiting the color palette with color quantization can scrape off another 10kB from the image while still maintaining its visual integrity.

Posterization

Posterization is a photographic technique of reducing colors in an image, producing distinct contours and areas of flat color. This effect is available in many photo editing suites, and can be applied instantly with imgix by making use of colorquant.

Advanced Stylistic Effects

Making use of colorquant along with the halftone parameter (htn), you can achieve even more stylized imagery while retaining detail.

Original
?colorquant=4&htn=4
Original
?colorquant=4&htn=2