For some time I have been playing around with writing games for Android. The game loads the graphics in form of image sprites, so I needed a way to easily stick several png images into one image. I though there would be tons of free applications available for this purpose, but I didn’t find any, so I decided to create my own sprite generator.
The code is short and simple. Please feel free to use it as you please! 🙂
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.*;
public class SpriteGenerator {
public static void main(String[] args) throws IOException {
if (args.length != 2)
{
System.out.print("Usage: SpriteGenerator {path to images} {output file}");
return;
}
String imagePath = args[0];
String outputFile = args[1];
File imageFolder = new File(imagePath);
File[] files = imageFolder.listFiles();
// Read images
ArrayList imageList = new ArrayList();
for (File f : files)
{
if (f.isFile())
{
String fileName = f.getName();
String ext = fileName.substring(fileName.lastIndexOf(".")+1,
fileName.length());
if (ext.equals("png"))
{
imageList.add(ImageIO.read(f));
}
}
}
// Find max width and total height
int maxWidth = 0;
int totalHeight = 0;
for (BufferedImage image : imageList)
{
totalHeight += image.getHeight();
if (image.getWidth() > maxWidth)
maxWidth = image.getWidth();
}
System.out.format("Number of images: %s, total height: %spx, width: %spx%n",
imageList.size(), totalHeight, maxWidth);
// Create the actual sprite
BufferedImage sprite = new BufferedImage(maxWidth, totalHeight,
BufferedImage.TYPE_INT_ARGB);
int currentY = 0;
Graphics g = sprite.getGraphics();
for (BufferedImage image : imageList)
{
g.drawImage(image, 0, currentY, null);
currentY += image.getHeight();
}
System.out.format("Writing sprite: %s%n", outputFile);
ImageIO.write(sprite, "png", new File(outputFile));
}
}
Output from a run:
java -classpath {...classpath hell...} SpriteGenerator ./images ./sprite.png
Number of images: 10, total height: 640px, width: 34px
Writing sprite: /Users/peter/Development/Android/HappyFrog/gfx/sprite.png