1

Hi everyone i have problems in converting GrayScale bmp images into integer 2D-array (with values 0-255) in Java.

I have a pmb image that could be seen as an integer(0-255) 2D-array and i want to see that 2D-array in a Java data structure

i tried this way:

Image image = ImageIO.read(new File("my_img.bmp"));
BufferedImage img = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_BYTE_GRAY);
Graphics g = img.createGraphics();
g.drawImage(image, 0, 0, null);
g.dispose();

Then with my BufferedImage i create int[][] this way:

int w = img.getWidth();
int h = img.getHeight();

int[][] array = new int[w][h];
for (int j = 0; j < w; j++) {
    for (int k = 0; k < h; k++) {
        array[j][k] = img.getRGB(j, k);
    }
}

But now all the 2D-array is full of number like "-9211021" or similar.

i think that the problem is in getRGB(j,k) but i don't know if it's possible to solve it.

edit:

i know RGB is not grayscale, so how can i get the grayscale value of a single pixel from a grayscale BufferedImage?

1

1 Answer 1

1

In a grayscale image, BufferedImage.getPixel(x,y) wont give values within the [0-255] range. Instead, it returns the corresponding value of a gray level(intensity) in the RGB colorspace. That's why you are getting values like "-9211021".

The following snippet should solve your problem :

Raster raster = image.getData();
for (int j = 0; j < w; j++) {
    for (int k = 0; k < h; k++) {
        array[j][k] = raster.getSample(j, k, 0);
    }
}

where image is the created BufferedImage. The 0 in the getSample indicates that we are accessing the first byte/band(setting it to a greater value will throw a ArrayOutOfBoundException in grayscale images).

Sign up to request clarification or add additional context in comments.

2 Comments

thanks for the reply, but i solved in one other way, by extracting a single channer from the RGB value in this way: array[i][j] = (bmp.getRGB(i, j) >> 16) & 0xFF;
Then you used RED channel(>>16). If that suffices your need, it's okay. However, to obtain graylevel from RGB, usually all three channel values are extracted and converted as : I = .299 * R + .587 * G + .114 * B only ~34% of the R value is considered for the intensity.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.