簡體   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