Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read a .bmp file identify which pixels are black in Java

Something like the following... except making it work:

public void seeBMPImage(String BMPFileName) throws IOException {
BufferedImage image = ImageIO.read(getClass().getResource(BMPFileName));

    int[][] array2D = new int[66][66];

for (int xPixel = 0; xPixel < array2D.length; xPixel++)
    {
        for (int yPixel = 0; yPixel < array2D[xPixel].length; yPixel++)
        {
            int color = image.getRGB(xPixel, yPixel);
            if ((color >> 23) == 1) {
                array2D[xPixel][yPixel] = 1;
            } else {
                array2D[xPixel][yPixel] = 1;
            }
        }
    }
}
like image 771
Wang-Zhao-Liu Q Avatar asked Oct 04 '22 21:10

Wang-Zhao-Liu Q


1 Answers

I would use this:

public void seeBMPImage(String BMPFileName) throws IOException {
    BufferedImage image = ImageIO.read(getClass().getResource(BMPFileName));

    int[][] array2D = new int[image.getWidth()][image.getHeight()];

    for (int xPixel = 0; xPixel < image.getWidth(); xPixel++)
        {
            for (int yPixel = 0; yPixel < image.getHeight(); yPixel++)
            {
                int color = image.getRGB(xPixel, yPixel);
                if (color==Color.BLACK.getRGB()) {
                    array2D[xPixel][yPixel] = 1;
                } else {
                    array2D[xPixel][yPixel] = 0; // ?
                }
            }
        }
    }

It hides all the details of RGB to you and is more comprehensible.

like image 55
mmirwaldt Avatar answered Oct 07 '22 19:10

mmirwaldt