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));
$size = 0;
for ($i = 0; $i < $pixelCount; $i = $i + $quality) {
$x = $startX + $i % $width;
$y = (int) ($startY + $i / $width);
$color = $image->getPixelColor($x, $y);
if (static::isClearlyVisible($color) && static::isNonWhite($color)) {
$pixelArray[$size++] = static::getColorIndex($color->red, $color->green, $color->blue, 8);
// TODO : Compute directly the histogram here ? (save one iteration over all pixels)
}
}
$pixelArray->setSize($size);
// Don't destroy a resource passed by the user !
// TODO Add a method in ImageLoader to know if the image should be destroy (or to know the detected image source type)
if (is_string($sourceImage)) {
$image->destroy();
}
return $pixelArray;
}