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

像下面的东西…除了使其工作:

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 > 23) == 1) { array2D[xPixel][yPixel] = 1; } else { array2D[xPixel][yPixel] = 1; } } } } 

我会用这个:

 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的所有细节,更易于理解。

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

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