0

I'm not sure where to start on this one, but is there a way I can use Java to scan an image row by row for a specific color, and pass all of the positions into and ArrayList?

Mr. Mittens
  • 69
  • 4
  • 14

2 Answers2

2

Can you? yes. Here's how:

    ArrayList<Point> list = new ArrayList<Point>();
    BufferedImage bi= ImageIO.read(img); //Reads in the image

    //Color you are searching for
    int color= 0xFF00FF00; //Green in this example
    for (int x=0;x<width;x++)
        for (int y=0;y<height;y++)
            if(bi.getRGB(x,y)==color)
                list.add(new Point(x,y));
Jason
  • 13,563
  • 15
  • 74
  • 125
0

Try using a PixelGrabber. It accepts an Image or ImageProducer.

Here's an example adapted from the documentation:

 public void handleSinglePixel(int x, int y, int pixel) {
      int alpha = (pixel >> 24) & 0xff;
      int red   = (pixel >> 16) & 0xff;
      int green = (pixel >>  8) & 0xff;
      int blue  = (pixel      ) & 0xff;
      // Deal with the pixel as necessary...
 }

 public void handlePixels(Image img, int x, int y, int w, int h) {
      int[] pixels = new int[w * h];
      PixelGrabber pg = new PixelGrabber(img, x, y, w, h, pixels, 0, w);
      try {
          pg.grabPixels();
      } catch (InterruptedException e) {
          System.err.println("interrupted waiting for pixels!");
          return;
      }
      if ((pg.getStatus() & ImageObserver.ABORT) != 0) {
          System.err.println("image fetch aborted or errored");
          return;
      }
      for (int j = 0; j < h; j++) {
          for (int i = 0; i < w; i++) {
              handleSinglePixel(x+i, y+j, pixels[j * w + i]);
          }
      }
 }

In your case, you would have:

public void handleSinglePixel(int x, int y, int pixel) {
      int target = 0xFFABCDEF; // or whatever
      if (pixel == target) {
          myArrayList.add(new java.awt.Point(x, y));
      }
 }
wchargin
  • 15,589
  • 12
  • 71
  • 110