Error executing class with parameter by main

3

I'm trying to compile my code through cmd by passing the image parameter (name and format). But it returns me this error.

java ImageSplit tileset.png

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
        at ImageSplit.main(ImageSplit.java:33)

The code is this:

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class ImageSplit {

    private static int width = 0;
    private static int height = 0;
    private static final int tileSize = 16;

    private BufferedImage readImage(String caminho) {

        BufferedImage bi = null;
        try {
            bi = ImageIO.read(new File(
                    getClass().getResource(caminho).getFile()));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bi;
    }

    public static void main(String[] args) {

        ImageSplit imageSplit = new ImageSplit();
        BufferedImage image = null; 
        if(args.length < 1) {
            System.out.println("Informe o parametro da imagem.");
            return;
        }
        image = imageSplit.readImage(args[1]);
        width = image.getWidth() / tileSize; // Col, tile
        height = image.getHeight() / tileSize; // Row, tile
        BufferedImage[] subImages = new BufferedImage[width * height];
        for(int i=0; i<height; i++) {
            for(int j=0; j<width; j++) {
                subImages[i * width + j] = image.getSubimage(j * 16, i * 16, tileSize, tileSize);
            }
        }
        for(int i=0; i<subImages.length; i++) {
            try {
                ImageIO.write(subImages[i], "tile" + i + ".png", new File("./Tiles"));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

And the image is in the same folder as the class.

    
asked by anonymous 21.12.2017 / 00:37

1 answer

2

I think the error is in this line:

image = imageSplit.readImage(args[1]);

As you are only passing one argument to main (only tileset.png ), the correct one is to get the first index of args[] , which is 0 and not 1. Change as below:

image = imageSplit.readImage(args[0]);

In java, list indexes and arrays start with 0 and go to tamanho da lista(array)-1 .

    
21.12.2017 / 00:53