Java BufferedImage.getRGB() - 协调越界

时间:2015-01-25 20:28:07

标签: java bufferedimage

所以,我试图尝试BufferedImage中特定像素的颜色...

public void LoadImageLevel (BufferedImage image) {

    int w = image.getWidth ();
    int h = image.getHeight ();

    System.out.println (w + " " + h);

    for (int xx = 0; xx < h; xx++) {

        for (int yy = 0; yy < w; yy++) {

            int pixel = image.getRGB (xx, yy);

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

            if (red == 255 && green == 255 && blue == 255) {

                handler.addObject (new Block (xx * 32, yy * 32, ObjectID.Block, 32, 32));
            }
        }
    }
}

它是从Main类构造函数调用的:

    ImageLoader imageLoader = new ImageLoader ();

    level = imageLoader.loadImage ("/levels/level_test.png");

    LoadImageLevel (level);

BufferedImage是从我的BufferedImageLoader类加载的:

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;

public class ImageLoader {

    private BufferedImage image;

    public BufferedImage loadImage (String path) {

        try {

            image = ImageIO.read (getClass ().getResource (path));

        } catch (IOException e) {

            e.printStackTrace ();
        }

        return image;
    }
}

当我运行项目时,我收到此错误:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:   Coordinate out of bounds!
    at sun.awt.image.ByteInterleavedRaster.getDataElements(Unknown Source)
    at java.awt.image.BufferedImage.getRGB(Unknown Source)
    at com.main.index.Game.LoadImageLevel(Game.java:190)
    at com.main.index.Game.<init>(Game.java:41)
    at com.main.index.Game.main(Game.java:206)

第190行是&#34; int pixel = image.getRGB(xx,yy);&#34;,第41行是在构造函数中调用的地方,第206行是主要方法。


提前致谢! ^ _ ^

3 个答案:

答案 0 :(得分:2)

问题出在这里:

int pixel = image.getRGB (xx, yy);

应该是:

int pixel = image.getRGB (yy, xx);

答案 1 :(得分:1)

你的xx从0变为高度,而不是从0变为宽度。你的yy从0变为宽度,而不是从0变为高度。

答案 2 :(得分:1)

level = imageLoader.loadImage ("/levels/level_test.png");

您使用的图像应小于主窗口的总宽度和高度。在这种情况下,采用RGB值拍摄尺寸为2 ^ X的图片,其中X = 1,2,3,4,5,6,7,8,9 ...... ..

试试这个: 将level_test.png调整为512 x 512像素。

上面是解决方案,因为Array包含边界。

java.lang.ArrayIndexOutOfBoundsException:   Coordinate out of bounds!
at sun.awt.image.ByteInterleavedRaster.getDataElements(Unknown Source)