1

I wrote the function below. It switches out one color for another. The pictures going in are css sprites with various colors and a white background.

So.. sprite 1 might by blue and sprite 2 might be green.

The function would be run twice to replace the blue + green with whatever colors were required.

/**
 * Changes the color of a graphic.
 * $settings = array (
 *  'icon'
 *  'new_icon'
 *  'old_color' = array
 *  'new_color' = array
 * );
*/
function updateIconColor($settings=array()) {
    // Create Image
    $image = imagecreatefrompng($settings['icon']);

    // Convert True color image to a palatte
    imagetruecolortopalette($image, false, 255);

    // Restore Alpha
    $white = imagecolorclosest($image, 255, 255, 255);
    imagecolortransparent($image, $white);

    // Find + Set color
    $index = imagecolorclosest($image, $settings['old_color'][0],$settings['old_color'][1],$settings['old_color'][2]);
    imagecolorset($image, $index, $settings['new_color'][0], $settings['new_color'][1], $settings['new_color'][2]);

    // Restore Alpha
    imageAlphaBlending($image, true);
    imageSaveAlpha($image, true);

    // Save
    imagepng($image, $settings['new_icon']); // save image as gif
    imagedestroy($image);
}

I need to allow dithering on these images. Is there a way this function can be modified to either cope with dithered images or add dithering itself?

John Paul
  • 59
  • 1
  • 2
  • 7

1 Answers1

1

To add dithering in the palette conversion, change:

imagetruecolortopalette($image, false, 255);

to:

imagetruecolortopalette($image, true, 255);
  • Doing this has no effect on non-dithered sprites. Adding this parameter to dithered sprites makes them go speckly. This doesn't aid color conversion. – John Paul Apr 13 '11 at 14:57
  • The outcome of the dither depends on the number of colors used in the source images and the number specified in the 3rd parameter. However, the PHP manual states that the imagetruecolortopalette-function sometimes "does not work as well as might be hoped"... – Tobias Einarsson Apr 13 '11 at 18:07