有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java getSubimage为我提供了期望值null

我试图用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());
        }
    }

你知道我为什么一直收到预期错误1:null吗


共 (1) 个答案

  1. # 1 楼答案

    我不确定您为什么要迭代宽度/高度的数量,但我假设您希望迭代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有关,如果您在运行时使用意外的最大x/y量初始化indexOutOfBoundsException,则可能是indexOutOfBoundsException