getSubimage 给了我期望 null

getSubimage gives me expection null

我正在尝试用 java 制作国际象棋游戏,我从 google 那里得到了棋子的图像。 现在我想把它剪成 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());
        }
    }

知道为什么我总是收到 Expection error1: null

我不确定你为什么要遍历 width/height 的数量,但我想你想遍历 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 的最大数量为 x/y,则可能是 indexOutOfBoundsException在运行期间。