java - getSubimage 给了我期望 null

标签 java image javax.imageio

我正在尝试用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/

相关文章:

java - 我尝试使用的 JPanel 的令人困惑的属性

java - Java 判断一张图片是否为灰度

java - Driver.getConnection 使用 SQLServer 驱动程序和 Java 1.6.0_29 挂起

java - 替换 LinkedList 中的节点实际上并没有替换任何内容

django - 在 django : getting "global name context is not defined" error 中上传图片

jquery - 图片加载性能

java - 使用不同文件夹中的图像链接 (Java)

java - 读取图像时出现 OutOfMemory 错误

java - 如何在 Java 中迭代地查找树的深度?

java - 什么是NullPointerException,我该如何解决?