2

I programmed something like paint. I have JPanel and I can draw on it.I'm using only black line. I wanna convert it to binary array, where 1 is when pixel is black, 0 when is white (background). It's possible? How to do this?

OnTheFly
  • 2,059
  • 5
  • 26
  • 61
  • http://stackoverflow.com/questions/113897/how-do-i-get-the-image-paint-paintcomponent-generates should help you getting started – Robin Dec 15 '11 at 19:11

1 Answers1

2

In a nutshell, create a BufferedImage with the same dimensions as your JPanel and paint the panel to the image. Then you can iterate over the image raster to get the sequence of pixel color values corresponding to black and white. For example

// Paint the JPanel to a BufferedImage.
Dimension size = jpanel.getSize();
int imageType = BufferedImage.TYPE_INT_ARGB;
BufferedImage image = BufferedImage(size.width, size.height, imageType);
Graphics2D g2d = image.createGraphics();
jpanel.paint(g2);

// Now iterate the image in row-major order to test its pixel colors.
for (int y=0; y<size.height; y++) {
  for (int x=0; ix<size.width; x++) {
    int pixel = image.getRGB(x, y);
    if (pixel == 0xFF000000) {
      // Black (assuming no transparency).
    } else if (pixel == 0xFFFFFFFF) {
      // White (assuming no transparency).
    } else {
      // Some other color...
    }
  }
}
maerics
  • 151,642
  • 46
  • 269
  • 291
  • See also [ComponentImageCapture.java](http://stackoverflow.com/questions/5853879/java-swing-obtain-image-of-jframe/5853992#5853992). – Andrew Thompson Dec 15 '11 at 19:35