How do you convert an image to black and white in PHP

匿名 (未验证) 提交于 2019-12-03 02:12:02

问题:

How does one go about converting an image to black and white in PHP?

Not just turning it into greyscale but every pixel made black or white?

回答1:

Simply round the grayscale color to either black or white.

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


回答2:

Using the php gd library:

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

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



回答3:

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



回答4:

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



回答5:

$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;} 


回答6:

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);  } 


回答7:

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

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

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

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



回答8:

Using the php gd library:

imagefilter($im, IMG_FILTER_GRAYSCALE); imagefilter($im, IMG_FILTER_CONTRAST, 1000); 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!