I am trying to get every single color of every single pixel of an image. My idea was following:
int[] pixels;
BufferedImage image;
image = ImageIO.read(this
I know this has already been answered, but the answers given are a bit convoluted and could use improvement. The simple idea is to just loop through every (x,y) pixel in the image, and get the color of that pixel.
BufferedImage image = MyImageLoader.getSomeImage();
for ( int x = 0; x < image.getWidth(); x++ ) {
for( int y = 0; y < image.getHeight(); y++ ) {
Color pixel = new Color( image.getRGB( x, y ) );
// Do something with pixel color here :)
}
}
You could then perhaps wrap this method in a class, and implement Java's Iterable API.
class IterableImage implements Iterable {
private BufferedImage image;
public IterableImage( BufferedImage image ) {
this.image = image;
}
@Override
public Iterator iterator() {
return new Itr();
}
private final class Itr implements Iterator {
private int x = 0, y = 0;
@Override
public boolean hasNext() {
return x < image.getWidth && y < image.getHeight();
}
@Override
public Color next() {
x += 1;
if ( x >= image.getWidth() ) {
x = 0;
y += 1;
}
return new Color( image.getRGB( x, y ) );
}
}
}
The usage of which might look something like the following
BufferedImage image = MyImageLoader.getSomeImage();
for ( Color color : new IterableImage( image ) ) {
// Do something with color here :)
}