我正在使用方法BufferedImage.getRGB(...)
从int
获取BufferedImage
的数组,但是当我尝试访问int
中的ArrayIndexOutOfBounds
时数组,我得到一个int
例外。我想要存储这些值的0
数组似乎长度为import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
public class SpriteSheet {
public String path;
public int width, height;
public int[] pixels;
public SpriteSheet(String path){
BufferedImage image = null;
try {
image = ImageIO.read(SpriteSheet.class.getResourceAsStream(path));
} catch (IOException e) {
e.printStackTrace();
}
if (image == null){
return;
}
this.path = path;
this.width = image.getWidth();
this.width = image.getHeight();
pixels = image.getRGB(0, 0, width, height, pixels, 0, width);
for (int i = 0; i < pixels.length; i++){
pixels[i] = (pixels[i] & 0xff)/64; // remove alpha channel
}
for (int i = 0; i < 8; i++){
System.out.println(pixels[i]);
}
}
}
,即使它看起来像图像已正确加载。我在哪里做错了?
以下是代码:
ArrayIndexOutOfBounds
当我尝试显示int的值时,{{1}}被抛出到最后一个循环中。
答案 0 :(得分:1)
更改
this.width = image.getWidth();
this.width = image.getHeight();
要
this.width = image.getWidth();
this.height = image.getHeight(); // set height properly
更改
for (int i = 0; i < 8; i++) {
要
for (int i = 0; i < pixels.length; i++) {