[ACCEPTED]-How do you convert an image to black and white in PHP-imagefilter

Accepted answer
Score: 27

Using the php gd library:

imagefilter($im, IMG_FILTER_GRAYSCALE);
imagefilter($im, IMG_FILTER_CONTRAST, -100);

Check the user comments 1 in the link above for more examples.

Score: 12

Simply round the grayscale color to either 1 black or white.

float gray = (r + g + b) / 3
if(gray > 0x7F) return 0xFF;
return 0x00;
Score: 6

You could shell out to imagemagick, assuming 3 your host supports it. What function do 2 you want to use for deciding if a pixel 1 should be black or white?

Score: 2

If you intend to do this yourself, you will 2 need to implement a dithering algorithm. But as @jonni says, using 1 an existing tool would be much easier?

Score: 1
$rgb = imagecolorat($original, $x, $y);
        $r = ($rgb >> 16) & 0xFF;
        $g = ($rgb >> 8 ) & 0xFF;
        $b = $rgb & 0xFF;

        $gray = $r + $g + $b/3;
        if ($gray >0xFF) {$grey = 0xFFFFFF;}
        else { $grey=0x000000;}

0

Score: 1

This function work like a charm

    public function ImageToBlackAndWhite($im) {

    for ($x = imagesx($im); $x--;) {
        for ($y = imagesy($im); $y--;) {
            $rgb = imagecolorat($im, $x, $y);
            $r = ($rgb >> 16) & 0xFF;
            $g = ($rgb >> 8 ) & 0xFF;
            $b = $rgb & 0xFF;
            $gray = ($r + $g + $b) / 3;
            if ($gray < 0xFF) {

                imagesetpixel($im, $x, $y, 0xFFFFFF);
            }else
                imagesetpixel($im, $x, $y, 0x000000);
        }
    }

    imagefilter($im, IMG_FILTER_NEGATE);

}

0

Score: 0

For each pixel you must convert from color 21 to greyscale - something like $grey = $red 20 * 0.299 + $green * 0.587 + $blue * 0.114; (these 19 are NTSC weighting factors; other similar 18 weightings exist. This mimics the eye's 17 varying responsiveness to different colors).

Then 16 you need to decide on a cut-off value - generally 15 half the maximum pixel value, but depending 14 on the image you may prefer a higher value 13 (make the image darker) or lower (make the 12 image brighter).

Just comparing each pixel 11 to the cut-off loses a lot of detail - ie 10 large dark areas go completely black - so 9 to retain more information, you can dither. Basically, start 8 at the top left of the image: for each pixel 7 add the error (the difference between the 6 original value and final assigned value) for 5 the pixels to the left and above before 4 comparing to the cut-off value.

Be aware 3 that doing this in PHP will be very slow 2 - you would be much further ahead to find 1 a library which provides this.

More Related questions