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.


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))
                        new Rectangle(0, 0, tileWidth, tileHeight),

                target.Save(outputFileName, ImageFormat.Jpeg);

Usage is pretty simple

var tiler = new ImageTile("image.png", 8, 8);


Tweet about this on TwitterShare on Google+Share on FacebookShare on RedditEmail this to someoneShare on LinkedInShare on StumbleUpon

Leave a Reply

Your email address will not be published. Required fields are marked *