繁体   English   中英

Java BufferedImage.getRGB()-坐标超出范围

[英]Java BufferedImage.getRGB () - Coordinate out of bounds

所以,我正在尝试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行是“ int pixel = image.getRGB(xx,yy);”,第41行是在构造函数中调用的位置,第206行是主要方法。


提前致谢! ^ _ ^

问题在这里:

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

它应该是:

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

您的xx从0到高度,而不是从0到宽度。 您的yy从0到宽度,而不是从0到高度。

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像素。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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