A simple image sprite generator in C#
Last week I posted the source code to a small program I wrote in Java to merge images into a sprite. This week I present the same application but in C#, pretty much translated line by line 🙂
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
namespace NSpriteGenerator
{
class Program
{
static void Main(string[] args)
{
if (args.Length != 2)
{
Console.WriteLine("Usage: NSpriteGenerator {path to images} {output file}");
return;
}
var imagePath = args[0];
var outputFile = args[1];
var imageFolder = new DirectoryInfo(imagePath);
// Read images
var imageList = imageFolder.GetFiles("*.png")
.Select(file => Image.FromFile(file.FullName));
// Find max width and total height
var maxWidth = 0;
var totalHeight = 0;
foreach(var image in imageList)
{
totalHeight += image.Height;
if (image.Width > maxWidth)
maxWidth = image.Width;
}
Console.WriteLine(string.Format("Number of images: {0}, total height: {1}px, width: {2}", imageList.Count(), totalHeight, maxWidth));
// Create the actual sprite
var currentY = 0;
using (var bitmap = new Bitmap(maxWidth, totalHeight))
{
using (var canvas = Graphics.FromImage(bitmap))
{
foreach (var image in imageList)
{
canvas.DrawImage(image, 0, currentY);
currentY += image.Height;
}
canvas.Save();
}
Console.WriteLine("Writing sprite: "+ outputFile);
bitmap.Save(outputFile, ImageFormat.Png);
}
}
}
}
Output from a run:
PS C:\dev\NSpriteGenerator> .\NSpriteGenerator.exe C:\temp\gfx c:\temp\sprite.png
Number of images: 10, total height: 640px, width: 34
Writing sprite: c:\temp\sprite.png