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

穿精又带淫゛_ 提交于 2019-12-05 17:07:29

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.

mmirwaldt's code is already on the right track.

However, if you want the array to visually represent the image:

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

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

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

When you print the array with a simple 2D array loop, it follows the pixel placement in the input image:

    for (int x = 0; x < array2D.length; x++)
    {
        for (int y = 0; y < array2D[x].length; y++)
        {
            System.out.print(array2D[x][y]);
        }
        System.out.println();
    }

Note: Modified lines are marked by //*.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!