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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top