private static function loadImage($sourceImage, $quality, array $area = null)
{
$loader = new ImageLoader();
$image = $loader->load($sourceImage);
$startx = 0;
$starty = 0;
$width = $image->getWidth();
$height = $image->getHeight();
if ($area) {
$startx = isset($area['x']) ? $area['x'] : 0;
$starty = isset($area['y']) ? $area['y'] : 0;
$width = isset($area['w']) ? $area['w'] : $width - $startx;
$height = isset($area['h']) ? $area['h'] : $height - $starty;
if ($startx + $width > $image->getWidth() || $starty + $height > $image->getHeight()) {
throw new \InvalidArgumentException("Area is out of image bounds.");
}
}
$pixelCount = $width * $height;
// Store the RGB values in an array format suitable for quantize function
// SplFixedArray is faster and more memory-efficient than normal PHP array.
$pixelArray = new SplFixedArray(ceil($pixelCount / $quality));
$j = 0;
for ($i = 0; $i < $pixelCount; $i = $i + $quality) {
$x = $startx + $i % $width;
$y = (int) ($starty + $i / $width);
$color = $image->getPixelColor($x, $y);
// If pixel is mostly opaque and not white
if ($color->alpha <= 62) {
if (!($color->red > 250 && $color->green > 250 && $color->blue > 250)) {
$pixelArray[$j++] = self::getColorIndex($color->red, $color->green, $color->blue, 8);
// TODO : Compute directly the histogram here ? (save one iteration over all pixels)
}
}
}
$pixelArray->setSize($j);
// Don't destroy a ressource passed by the user !
if (is_string($sourceImage)) {
$image->destroy();
}
return $pixelArray;
}