Question

    width = 25;
    height = 25;

    h1Walking = new BufferedImage[6];   
        BufferedImage sprite1 = ImageIO.read(new File(getClass().getResource("/Resources/kirbywalk.gif").toURI()));
        for(int i = 0; i < h1Walking.length; i++){
            h1Walking[i] = sprite1.getSubimage(
                    i * width + i,
        0,
        width,
        height
                );
        }

The code I have placed above is the part that is returning the error in my program. I don't understand why it is doing this does anyone have any idea's why it is returning the error below?

java.awt.image.RasterFormatException: (y + height) is outside of Raster
    at sun.awt.image.BytePackedRaster.createWritableChild(BytePackedRaster.java:1312)
    at java.awt.image.BufferedImage.getSubimage(BufferedImage.java:1196)
    at Main.Horses.<init>(Horses.java:72)
    at Main.HorseRacingGame.run(HorseRacingGame.java:113)
    at java.lang.Thread.run(Thread.java:695)
Was it helpful?

Solution

The RasterFormatException is coming from the getSubimage call here:

h1Walking[i] = sprite1.getSubimage(
    i * width + i,
    0,
    width,
    height
);

The getSubimage method takes x, y, width, and height as parameters where x and y are the coordinates of the top left pixel of the subimage (from javadoc).

A RasterFormatException is thrown if the subimage referenced by your parameters is not bounded by the image. So, something in your parameters is out of bounds of the image.

For your x, you are using i * width + i, but I believe you meant i * width. This will ensure that each vertical strip of the picture starts where the last one ended.

Additionally, the problem could be that using a constant width and height is giving you an error. Instead, you could consider doing sprite1.getWidth() / h1walking.length and similar for the height.

OTHER TIPS

Perhaps you are going over the pixel boundaries of "/Resources/kirbywalk.gif"

If you know the amount of subimages and that they are horizontally placed, maybe implement something like this:

// load the image
BufferedImage sprite1 = ImageIO.read(new File(getClass().getResource("/Resources/kirbywalk.gif").toURI()));
// declare ammount of cells in image
int num_of_cells = 6;
h1Walking = new BufferedImage[num_of_cells];
// find cell height and width based on the original image
int width = sprite1.getWidth()/ num_of_cells;
int height = sprite1.getHeight()

for(int i = 0; i < num_of_cells; i++)
    h1Walking[i] = sprite1.getSubimage( i *width,0,width,height);

By polling the image for the height and width you can be assured that all your points will remain within the gif limits.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top