How to to remove certain colors from an image with PHP or Ruby?

前端 未结 3 1761
南方客
南方客 2021-01-01 07:56

Say there are 3 circles: red, blue, black.

I only want the black circle to remain. How can I remove the red and blue circles?

相关标签:
3条回答
  • 2021-01-01 08:23

    Since you have asked for a PHP solution:

    • First load your picture with imagecreatefrompng or the similar functions for other image formats
    • Afterwards, use imagesx and imagesy to get the size of the image.
    • Now, what you can loop over all pixels via

      for ($i = 0; $i < $imageWidth; $i++) {
          for ($j = 0; $j < $imageHeight; $j++) {
              // check color and replace
          }
      }
      
    • Finally, use imagecolorat to get the color (check if it is in a specific range, don't take only black as a good color, but also all colors that have >= 250 at each value of red, green and blue for example)

    • ... and imagecolorset to set the color
    • Now you can save the image using imagepng for example.
    0 讨论(0)
  • 2021-01-01 08:27

    ImageMagick will do it. Just shell out to this command:

    convert circles.png -channel black -white-threshold 10% circles2.png
    

    You didn't say what to do with green. This script takes the easy way out and wipes out green as well. Actually, it wipes out anything not black.

    The RMagick libary lets you drive imagemagick with Ruby. Sadly, it's not working in my distro, so I can't prepare an example for you. However, using system or backtick to shell out to the command works just fine.

    0 讨论(0)
  • 2021-01-01 08:28

    If you know what image format that is being used, you could likely use that information to avoid accessing through pixel values (possibly destroying image quality), otherwise do something similar to this:

    1. Get hold of the image as an array of pixels
    2. Map over each pixel, setting it to the background color if it lies within a certain threshold step away from any of the colors you want to remove.

    This relies on that there is a given background color at any time that the pixels can be set to and that you can identify the colors to remove.

    0 讨论(0)
提交回复
热议问题