简体   繁体   中英

PixelGrabber.getPixels returns values out of the range 0-255

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM