/** * Return the average of the RGB value of two Image_Color2 objects. If * both objects have an alpha channel it will be averaged too. * <code> * $red = new Image_Color2('red'); * $blue = new Image_Color2('blue'); * $color = Image_Color2::average($red, $blue); * print $color->convertTo('named')->getString(); \/\/ 'purple' * </code> * * @param Image_Color2 $left Left color * @param Image_Color2 $right Right color * * @return Image_Color2 */ public static function average(Image_Color2 $left, Image_Color2 $right) { $lrgb = $left->getRgb(); $rrgb = $right->getRgb(); // remove the type element so we can properly compare lengths unset($lrgb['type']); unset($rrgb['type']); // the color may be RGB or RGBA, either way, they need to be the same // length. $size = min(count($lrgb), count($rrgb)); // find the average of each pair of elements $avg = array(); for ($i = 0; $i < $size; $i++) { $avg[] = (int) (($lrgb[$i] + $rrgb[$i]) / 2 + 0.5); } return new Image_Color2($avg); }
function testAverage_Rgba() { $red = new Image_Color2(array(255, 0, 0, 255)); $blue = new Image_Color2(array(0, 0, 255, 0)); $result = Image_Color2::average($red, $blue); $this->assertSame('Image_Color2', get_class($result)); $this->assertEquals(array(128, 0, 128, 128, 'type' => 'rgb'), $result->getArray()); }