问题
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;
}
}
}
}
回答1:
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.
回答2:
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 //*
.
来源:https://stackoverflow.com/questions/17015340/how-to-read-a-bmp-file-identify-which-pixels-are-black-in-java