class Pixel { public $r; public $g; public $b; public function __construct($r, $g, $b) { $this->r = $r; $this->g = $g; $this->b = $b; } } class PixelStack { /** * @var Pixel[] */ private $pixels = array(); public function getAverageRed() { $total = 0; $count = 0; foreach ($this->pixels as $pixel) { $total += $pixel->r; $count++; } return $total / $count; } public function getAverageGreen() { $total = 0; $count = 0; foreach ($this->pixels as $pixel) { $total += $pixel->g; $count++; } return $total / $count; } public function getAverageBlue() { $total = 0; $count = 0; foreach ($this->pixels as $pixel) { $total += $pixel->b; $count++; } return $total / $count; } public function pushPixel($r, $g, $b) { $pixel = new Pixel($r, $g, $b); array_push($this->pixels, $pixel); if (count($this->pixels) > 20) { array_shift($this->pixels); } } } function syncIteratorImage($image_path) { $imagick = new \Imagick(realpath($image_path)); $imageIterator = $imagick->getPixelRegionIterator(125, 100, 275, 200); /* Loop through pixel rows */ foreach ($imageIterator as $pixels) { $pixelStatck = new PixelStack(); /* Loop through the pixels in the row (columns) */ foreach ($pixels as $pixel) { /** @var $pixel \ImagickPixel */ $pixelStatck->pushPixel($pixel->getColorValue(\Imagick::COLOR_RED), $pixel->getColorValue(\Imagick::COLOR_GREEN), $pixel->getColorValue(\Imagick::COLOR_BLUE)); $color = sprintf("rgb(%d, %d, %d)", intval($pixelStatck->getAverageRed() * 255), intval($pixelStatck->getAverageGreen() * 255), intval($pixelStatck->getAverageBlue() * 255)); $pixel->setColor($color); } /* Sync the iterator, this is important to do on each iteration */ $imageIterator->syncIterator(); } header("Content-Type: image/jpeg"); echo $imagick; }