The setting of the number of colors is the core parameter, which directly determines how many colors the converted image can retain. The impact is mainly reflected in the following aspects:
When the number of colors is set too small (such as 16 or 32), a large number of colors in the image will be merged or approximated, and the details will be easily distorted, especially for photo-based images. This distortion usually manifests as:
Color blocking: The originally smooth color transition becomes abrupt.
Color drift: The color is far from the original image, and the visual effect is greatly reduced.
When the number of colors increases to 128 or 256, the image can basically retain most of the color levels, and the naked eye observation is almost the same as the original image. But this also means that the image file size is close to the original truecolor image, and the compression advantage is reduced.
To find the best balance between image quality and performance, we need to judge it in combination with image content and usage scenarios. Here are some practical suggestions:
Icons and graphical interface (UI) elements : can be set to 16~64 colors. Because there are fewer colors of this type of image itself, the loss after conversion is small.
Photos, gradient background images : It is recommended to set to 128 or 256 colors. This will better preserve image details.
Enabling $dither = true introduces a color jitter algorithm, simulating richer visual hierarchies with a small amount of colors. Especially when the number of colors is small, color blocks and contour jagging can be significantly reduced.
$image = imagecreatefromjpeg('https://gitbox.net/images/sample.jpg');
imagetruecolortopalette($image, true, 64);
This code limits the image to 64 colors and turns on jitter, which can be suitable for scenes that require image size but want to retain a certain quality.
For complex applications, the number of colors can be determined by analyzing the image color distribution dynamically. For example, perform color histogram analysis on the picture, determine its color diversity, and adjust the $ncolors value based on this.
Misconception: The less color, the better <br> Not all images are suitable for compressing colors, especially images that require fine details, as excessive compression can cause severe distortion.
Misconception: Turning on jitter is always better <br> While jitter can improve visual effects, it may introduce additional noise that affects the readability of the image in some contexts. Decide whether to enable it according to the requirements.
Suggestions: Cooperate with file format optimization <br> Saving the palette image as PNG-8 format can further reduce the volume. For example, use the imagepng() function to output.
imagepng($image, 'https://gitbox.net/images/optimized.png', 9);