0

I need to load an image, and get the values of the pixels of the image across breadth and width. I know I need to use PixelGrabber and Image but I'm unsure of how to do it. My code till now. (Assuming all the required libraries are imported and this in the try part)

File Image1 = new File("i1.jpg");
img1 = ImageIO.read(Image1);
int img1w, img1h;
PixelGrabber grabimg1 = new PixelGrabber(img1, 0, 0, -1, -1, false);
if (grabimg1.grabPixels())
{
    img1w = grabimg1.getWidth();
    img1h = grabimg1.getHeight();
    int[] data = (int[]) grabimg1.getPixels();
    for (int i= 0; i < img1h; i++)
    {
        for (int j= 0; j < img1w; j++)
        {
            System.out.println(data[i*img1w + j]);
        }
        System.out.println("\n");
    }
 }

Printing this prints out values from -1 to -16777216 , while I would like values from 0 - 255. Would be thankful for any help.

Buddha
  • 4,339
  • 2
  • 27
  • 51
Manoj
  • 961
  • 4
  • 11
  • 37

2 Answers2

1

The JavaDoc for PixelGrabber contains a way to convert between int and the actual RGB values:

  int alpha = (pixel >> 24) & 0xff;
  int red   = (pixel >> 16) & 0xff;
  int green = (pixel >>  8) & 0xff;
  int blue  = (pixel      ) & 0xff;

Alternatively you can use the ColorModel as returned by getColorModel().

TwoThe
  • 13,879
  • 6
  • 30
  • 54
  • Using the color model is probably safer. You don't want to make assumptions about how the bits for pixel color are packed. – William Morrison Jan 29 '14 at 17:05
  • There is an option to have the colors converted to this RGB model in the constructor. However he sets this explicitly to false. – TwoThe Jan 29 '14 at 17:06
  • @WilliamMorrison Are you talking about the last term in the constructor? I set that to true and nothing changed. – Manoj Jan 29 '14 at 17:18
  • Yes, that's what we're talking about. If nothing changed that means your color model was probably already RGB, though you should still construct pixelgrabber with `true`. Use the integer you get back, with TwoThe's code to get the pixel color. Problem solved! @Manoj – William Morrison Jan 29 '14 at 17:28
0

You should use BufferedImage. Then you can simply use the getRGB method.

Someone
  • 551
  • 3
  • 14