Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BufferedImage - Gray Scale

Given an image that is in grayscale, how would I get the pixel values of the grayscale at that location?

This outputs temp as -16777216 (black) all the time.

public void testMethod()
{
    int width = imgMazeImage.getWidth();
    int height = imgMazeImage.getHeight();

    //Assign class variable as a new image with RGB formatting
    imgMazeImage = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
    for(int i=0; i < width; i ++){
        for(int j=0; j < height; j++)
        {
            //Grab and set the colors one-by-one
            inttemp = imgMazeImage.getRGB(j, i);
            System.out.println(temp);
        }
    }
}
like image 822
RedLeader Avatar asked Feb 23 '26 00:02

RedLeader


1 Answers

you are creating a new blank image and assigning it to your class variable:

imgMazeImage = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);

the pixels are created with a default value and its logical that they all have the same color (black) at the stage when you are printing them since you did not manipulate the color in any pixel yet.

also, your code might fail if the width is not equal to the height. according to your for loops, i runs along width and j runs along height. therefore, you should change

int temp = imgMazeImage.getRGB(j, i);

to

int temp = imgMazeImage.getRGB(i, j);