Get color of each pixel of an image using BufferedImages

后端 未结 6 1368
南方客
南方客 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:16

    import java.awt.Color;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.IOException;
    import javax.imageio.ImageIO;
    
    public class ImageUtil {
    
        public static Color[][] loadPixelsFromImage(File file) throws IOException {
    
            BufferedImage image = ImageIO.read(file);
            Color[][] colors = new Color[image.getWidth()][image.getHeight()];
    
            for (int x = 0; x < image.getWidth(); x++) {
                for (int y = 0; y < image.getHeight(); y++) {
                    colors[x][y] = new Color(image.getRGB(x, y));
                }
            }
    
            return colors;
        }
    
        public static void main(String[] args) throws IOException {
            Color[][] colors = loadPixelsFromImage(new File("image.png"));
            System.out.println("Color[0][0] = " + colors[0][0]);
        }
    }
    

提交回复
热议问题