我正在尝试用java制作国际象棋游戏,我从谷歌获得了棋子的图像。 现在我想将其剪切为 6*2 图像(黑白图像)。但我不明白这个有什么问题。
public static final String PIECES_IMAGE_PATH = "Images/chess_pieces.png";
public static final int PIECE_IMAGES_INROW = 6;
public static final int PIECE_IMAGE_ROWS = 2;
BufferedImage[][] pieceIcons;
private void setupPieceImages(){
try {
BufferedImage image = ImageIO.read(new File(Config.PIECES_IMAGE_PATH));
int pieceImageWidth = image.getWidth()/Config.PIECE_IMAGES_INROW;
int pieceImageHeight = image.getHeight()/Config.PIECE_IMAGE_ROWS;
for(int x = 0; x < pieceImageHeight; x++){
for(int y = 0; y < pieceImageWidth; y++){
try{
pieceIcons[x][y] = image.getSubimage(x*pieceImageHeight,y*pieceImageWidth,pieceImageWidth,pieceImageHeight);
}catch(Exception e){
System.out.println("Error1: "+e.getMessage());
}
}
}
}catch(Exception e){
System.out.println("error2: "+e.getMessage());
}
}
知道为什么我不断收到 Expectation error1: null
最佳答案
我不确定为什么您要迭代宽度/高度的量,但我想您想迭代 2 行,每行 6 列(或者在本例中为 6 列,每列 2 行):
public static final String PIECES_IMAGE_PATH = "Images/chess_pieces.png";
public static final int PIECE_IMAGES_INROW = 6;
public static final int PIECE_IMAGE_ROWS = 2;
public static void main(String args[]) {
BufferedImage[][] pieceIcons = new BufferedImage[PIECE_IMAGES_INROW][PIECE_IMAGE_ROWS];
try {
BufferedImage image = ImageIO.read(new File(Try.class.getResource(PIECES_IMAGE_PATH).toURI()));
int pieceImageWidth = image.getWidth()/PIECE_IMAGES_INROW;
int pieceImageHeight = image.getHeight()/PIECE_IMAGE_ROWS;
for(int x = 0; x < PIECE_IMAGES_INROW; x++){
for(int y = 0; y < PIECE_IMAGE_ROWS; y++){
try{
pieceIcons[x][y] = image.getSubimage(x*pieceImageWidth,y*pieceImageHeight,pieceImageWidth,pieceImageHeight);
}catch(Exception e){
System.out.println("Error1: "+e.getMessage());
}
}
}
}catch(Exception e){
System.out.println("error2: "+e.getMessage());
}
}
您遇到的错误似乎与 Error1
有关,如果您使用意外的最大值初始化 pieceIcons
,则可能会出现 indexOutOfBoundsException
运行时期间的 x/y 量。
关于java - getSubimage 给了我期望 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60121721/