How to extract part of this image in Java?

Click Upvote picture Click Upvote · Mar 7, 2009 · Viewed 53.7k times · Source

I have this sprite sheet:

Pacman sprites

How can I read this image file to extract part of it to be used as a sprite ?

Answer

coobird picture coobird · Mar 7, 2009

If the sprites area read into a BufferedImage, the getSubimage method can be used to get a subimage of the sprite sheet.

The getSubimage method will take the x, y, and the width and height of the desired subimage, so the desired sprite can be obtained. Since most of the sprites seem to be the same size, I would think most of them can be retrieved by a nested for loop to iterate through the large image.

For example, if the sprite image is loaded using the ImageIO class (such as the read method), and each sprite is 10 pixels by 10 pixels in size, where are 5 rows by 5 columns of sprites, the sprites can be obtained by the following:

BufferedImage bigImg = ImageIO.read(new File("sheet.png"));
// The above line throws an checked IOException which must be caught.

final int width = 10;
final int height = 10;
final int rows = 5;
final int cols = 5;
BufferedImage[] sprites = new BufferedImage[rows * cols];

for (int i = 0; i < rows; i++)
{
    for (int j = 0; j < cols; j++)
    {
        sprites[(i * cols) + j] = bigImg.getSubimage(
            j * width,
            i * height,
            width,
            height
        );
    }
}

The catch is, of course, the above code will only work if all the sprites are the same size, so there will need to be some adjustment performed in order to work for the given sprite sheet. (As the top right-hand corner seems to be different in size from the others.)