Quantcast
Channel: source code bean » C#
Viewing all articles
Browse latest Browse all 10

A simple image sprite generator in C#

$
0
0

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 :)

  1. using System;
  2. using System.Drawing;
  3. using System.Drawing.Imaging;
  4. using System.IO;
  5. using System.Linq;
  6.  
  7. namespace NSpriteGenerator
  8. {
  9.     class Program
  10.     {
  11.         static void Main(string[] args)
  12.         {
  13.             if (args.Length != 2)
  14.             {
  15.                 Console.WriteLine("Usage: NSpriteGenerator {path to images} {output file}");
  16.                 return;
  17.             }
  18.  
  19.             var imagePath = args[0];
  20.             var outputFile = args[1];
  21.            
  22.             var imageFolder = new DirectoryInfo(imagePath);
  23.            
  24.  
  25.             // Read images
  26.             var imageList = imageFolder.GetFiles("*.png")
  27.                     .Select(file => Image.FromFile(file.FullName));
  28.  
  29.  
  30.             // Find max width and total height
  31.             var maxWidth = 0;
  32.             var totalHeight = 0;
  33.  
  34.             foreach(var image in imageList)
  35.             {
  36.                 totalHeight += image.Height;
  37.  
  38.                 if (image.Width > maxWidth)
  39.                     maxWidth = image.Width;
  40.             }
  41.  
  42.             Console.WriteLine(string.Format("Number of images: {0}, total height: {1}px, width: {2}", imageList.Count(), totalHeight, maxWidth));
  43.  
  44.  
  45.             // Create the actual sprite
  46.             var currentY = 0;
  47.  
  48.             using (var bitmap = new Bitmap(maxWidth, totalHeight))
  49.             {
  50.                 using (var canvas = Graphics.FromImage(bitmap))
  51.                 {
  52.                     foreach (var image in imageList)
  53.                     {
  54.                         canvas.DrawImage(image, 0, currentY);
  55.                         currentY += image.Height;
  56.                     }
  57.                     canvas.Save();
  58.                 }
  59.  
  60.                 Console.WriteLine("Writing sprite: "+ outputFile);
  61.                 bitmap.Save(outputFile, ImageFormat.Png);
  62.             }
  63.         }
  64.     }
  65. }
  66.  

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


Viewing all articles
Browse latest Browse all 10

Trending Articles