drstein
drstein

Reputation: 1113

grayscale bitmap into 2d array

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?

Upvotes: 1

Views: 6214

Answers (1)

blackSmith
blackSmith

Reputation: 3154

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).

Upvotes: 1

Related Questions