【问题标题】:Java BufferedImage.getRGB () - Coordinate out of boundsJava BufferedImage.getRGB() - 坐标越界
【发布时间】:2015-03-24 08:00:13
【问题描述】:

所以,我正在尝试 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行是main方法。


提前致谢! ^_^

【问题讨论】:

    标签: java bufferedimage


    【解决方案1】:

    问题来了:

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

    应该是:

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 谢谢,甚至没有意识到...谢谢:D!
      【解决方案3】:
      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)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-16
        • 1970-01-01
        • 2013-11-08
        • 2016-04-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多