How to read .bmp file, determine which pixels are black in Java

Something like the following ... except that it works:

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; } } } } 
+4
source share
2 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 understandable.

+3
source

mmirwaldt code is already on the right track.

However, if you want the array to visually display 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 an array using a simple 2D array loop, it follows the placement of pixels 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. Changed lines are marked //* .

0
source

Source: https://habr.com/ru/post/1485337/


All Articles