Get color of each pixel of an image using BufferedImages

后端 未结 6 1369
南方客
南方客 2020-11-29 06:49

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         


        
6条回答
  •  悲哀的现实
    2020-11-29 07:14

    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 :)
    }
    

提交回复
热议问题