[英]BufferedImage.getRGB does not return array
我使用的方法BufferedImage.getRGB(...)
來獲得數組int
的從BufferedImage
,但是當我試圖訪問這些int
'S的陣列中,我得到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]);
}
}
}
當我嘗試顯示int的值時,將在最后一個for循環中拋出ArrayIndexOutOfBounds
。
更改
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++) {
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.