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

后端 未结 7 1559
长情又很酷
长情又很酷 2020-12-01 14:34

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?

7条回答
  •  情深已故
    2020-12-01 15:20

    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.

提交回复
热议问题