如何读取.bmp文件来识别Java中哪些像素是黑色的

时间:2013-06-09 23:51:49

标签: java image file-io bmp

以下内容......除了使其有效之外:

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;
            }
        }
    }
}

2 个答案:

答案 0 :(得分:3)

我会用这个:

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; // ?
                }
            }
        }
    }

它隐藏了RGB的所有细节,并且更易于理解。

答案 1 :(得分:0)

mmirwaldt 的代码已经在正确的轨道上了。

但是,如果您希望数组直观地表示图像:

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; // ?
            }
        }
    }
}

使用简单的2D数组循环打印数组时,它会跟随输入图像中的像素位置:

    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();
    }

注意:修改后的行标有//*