Error executing class with parameter by main

Asked

Viewed 68 times

3

I am trying to compile my code by cmd, 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.

1 answer

2


I believe the error lies in this line:

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

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

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

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

  • That worked, I just don’t understand why you’re not recording the images.

  • @Roodrigo ai is already another problem other than the question. I suggest you close this question by marking the answer as accepted(by clicking on v) and open a new question with this new doubt. Do not forget to provide a [mcve] so we can test the code :)

  • 1

    Downvoter, what is wrong that can improve in the answer? Or the vote was only implied even?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.