Simple Image Tiling in C#
14
May
So, you want to cut up an image into tiles? Here is a simple C# class, ImageTile, that lets you provide an X and Y grid size and slice up a source image.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
public class ImageTile { private Image image; private Size size; public ImageTile(string inputFile, int xSize, int ySize) { if (!File.Exists(inputFile)) throw new FileNotFoundException(); image = Image.FromFile(inputFile); size = new Size(xSize, ySize); } public void GenerateTiles(string outputPath) { int xMax = image.Width; int yMax = image.Height; int tileWidth = xMax / size.Width; int tileHeight = yMax / size.Height; if (!Directory.Exists(outputPath)) { Directory.CreateDirectory(outputPath); } for (int x = 0; x < size.Width; x++) { for (int y = 0; y < size.Height; y++) { string outputFileName = Path.Combine(outputPath, string.Format("{0}_{1}.jpg", x, y)); Rectangle tileBounds = new Rectangle(x * tileWidth, y * tileHeight, tileWidth, tileHeight); Bitmap target = new Bitmap(tileWidth, tileHeight); using (Graphics graphics = Graphics.FromImage(target)) { graphics.DrawImage( image, new Rectangle(0, 0, tileWidth, tileHeight), tileBounds, GraphicsUnit.Pixel); } target.Save(outputFileName, ImageFormat.Jpeg); } } } } |
Usage is pretty simple
1 2 |
var tiler = new ImageTile("image.png", 8, 8); tiler.GenerateTiles("outputdirectory"); |