Read sprite sheet and return BufferedImage - Java 2D Graphics

Java examples for 2D Graphics:BufferedImage

Description

Read sprite sheet and return BufferedImage

Demo Code


//package com.java2s;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class Main {
    /**// w  ww.j a  v a 2 s. c  o  m
     * Read sprite sheet.
     *
     * @param fileName the file name
     * @param rows the rows
     * @param cols the columns
     * @param width the width
     * @param height the height
     * @return the buffered image[]
     * @throws IOException Signals that an I/O exception has occurred.
     */
    public static BufferedImage[] readSpriteSheet(String fileName,
            int rows, int cols, int width, int height) throws IOException {
        BufferedImage bigImg = ImageIO.read(new File(fileName));
        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(i * width, j
                        * height, width, height);
            }
        }

        return sprites;
    }
}

Related Tutorials