Grafika\Gd\Filter\Dither::ordered PHP Method

ordered() private method

Dither by applying a threshold map.
private ordered ( Image $image ) : Image
$image Grafika\Gd\Image
return Grafika\Gd\Image
    private function ordered($image)
    {
        // Localize vars
        $width = $image->getWidth();
        $height = $image->getHeight();
        $old = $image->getCore();
        $new = imagecreatetruecolor($width, $height);
        $thresholdMap = array(array(15, 135, 45, 165), array(195, 75, 225, 105), array(60, 180, 30, 150), array(240, 120, 210, 90));
        for ($y = 0; $y < $height; $y += 1) {
            for ($x = 0; $x < $width; $x += 1) {
                $color = imagecolorat($old, $x, $y);
                $r = $color >> 16 & 0xff;
                $g = $color >> 8 & 0xff;
                $b = $color & 0xff;
                $gray = round($r * 0.3 + $g * 0.59 + $b * 0.11);
                $threshold = $thresholdMap[$x % 4][$y % 4];
                $oldPixel = ($gray + $threshold) / 2;
                if ($oldPixel <= 127) {
                    // Determine if black or white. Also has the benefit of clipping excess value
                    $newPixel = 0;
                } else {
                    $newPixel = 255;
                }
                // Current pixel
                imagesetpixel($new, $x, $y, imagecolorallocate($new, $newPixel, $newPixel, $newPixel));
            }
        }
        imagedestroy($old);
        // Free resource
        // Create new image with updated core
        return new Image($new, $image->getImageFile(), $width, $height, $image->getType());
    }