. */ /** * This file contains the ColorReplace filter class. * * @author Dinu Florin * @package Modules * @subpackage Images */ /** * ColorReplace filter class. * * @author Dinu Florin * @package Modules * @subpackage Images */ class OldColorReplace extends AbstractImageFilter { protected $oldColor = null; protected $newColor = null; protected $fuzzyness = null; /** * Constructor. * * @param mixed $oldColor The color to replace. * @param mixed $newColor The new color. * @param number $fuzzyness The fuzzyness of the color replacement. * @note The colors can be either CSS-style ('#FFFFFF') or arrays (array('r', 'g', 'b')). */ public function __construct($oldColor, $newColor, $fuzzyness = 60) { $this->oldColor = Image::rgbToHsv((is_string($oldColor) && $oldColor{0} == '#')?Image::decodeColor($oldColor):$oldColor); $this->newColor = Image::rgbToHsv((is_string($newColor) && $newColor{0} == '#')?Image::decodeColor($newColor):$newColor); $this->fuzzyness = $fuzzyness; } /** * Apply to an image * * @param Image $image The image to apply the filter to */ public function applyTo(Image $image) { $img = $image->getResource(); $satThreshold = 1/(2*$this->fuzzyness); //Saturation threshold $halfFuzzyness = $this->fuzzyness/2; $imgw = $image->width; $imgh = $image->height; for($y = 0; $y < $imgh; $y++) { for($x = 0; $x < $imgw; $x++) { $pixelColor = imagecolorat($img, $x, $y); $pixelColor = imagecolorsforindex($img, $pixelColor); //We need the RGB components to be floats between 0 and 1 $pixelColor['r'] = $pixelColor['red']; $pixelColor['g'] = $pixelColor['green']; $pixelColor['b'] = $pixelColor['blue']; $pixelColor = Image::rgbToHsv($pixelColor); //Switch to HSV space $distance = max($this->oldColor['h'], $pixelColor['h']) - min($this->oldColor['h'], $pixelColor['h']); //The angle between the colors (hues) if($distance < $halfFuzzyness && $pixelColor['s'] > $satThreshold) //Do we need to replace this pixel? { $pixelColor['h'] = $this->newColor['h'] - $this->oldColor['h'] + $pixelColor['h']; $pixelColor['s'] = min(max($this->newColor['s']- $this->oldColor['s'] + $pixelColor['s'] , 0), 1); $pixelColor = Image::hsvToRgb($pixelColor); //Go back to RGB space $pixelColor = imagecolorallocate($img, $pixelColor['r'], $pixelColor['g'], $pixelColor['b']); imagesetpixel($img, $x, $y, $pixelColor); } } } $image->setResource($img); } } ?>