A simple image sprite generator in Java
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
Thank you for your post. I’ve used your software over the last few days to make image sprites for the web. I’ve modified it so that it takes in one extra parameter to specify a margin between images which is useful for the web.
One interesting note is that Microsoft GDI uses a 16bit int to store PNG dimensions. This means the max size of a png for use in Microsoft platforms is 32,767px in either direction. Took me half a day to figure out that reason windows browsers would not show the png file.
That’s great to hear! I had no idea that GDI uses 16bit ints for the dimensions, you must be merging quite a few images to reach images of that size 🙂