Split image files in C#

[example]

This example shows how you can split image files into smaller pieces.

Recently I needed separate bitmap files for the icons in the Visual Studio toolbox. I took a screen shot and then, rather than splitting the icons apart manually, I wrote this program to do it. The following code does most of the work.

// Split the file.
private void btnGo_Click(object sender, EventArgs e)
{
    // Get the inputs.
    int wid = int.Parse(txtWidth.Text);
    int hgt = int.Parse(txtHeight.Text);
    Bitmap bm = LoadUnlocked(txtFile.Text);

    // Start splitting the Bitmap.
    string piece_name =
        Path.GetFileNameWithoutExtension(txtFile.Text);
    Bitmap piece = new Bitmap(wid, hgt);
    Rectangle dest_rect = new Rectangle(0, 0, wid, hgt);
    using (Graphics gr = Graphics.FromImage(piece))
    {
        int num_rows = bm.Height / hgt;
        int num_cols = bm.Width / wid;
        Rectangle source_rect = new Rectangle(0, 0, wid, hgt);
        for (int row = 0; row < num_rows; row++)
        {
            source_rect.X = 0;
            for (int col = 0; col < num_cols; col++)
            {
                // Copy the piece of the image.
                gr.DrawImage(bm, dest_rect, source_rect,
                    GraphicsUnit.Pixel);

                // Save the piece.
                string filename = piece_name +
                    row.ToString("00") +
                    col.ToString("00") + ".bmp";
                piece.Save(filename, ImageFormat.Bmp);

                // Move to the next column.
                source_rect.X += wid;
            }
            source_rect.Y += hgt;
        }
        MessageBox.Show(
            "Created " + num_rows * num_cols + " files",
            "Done", MessageBoxButtons.OK,
            MessageBoxIcon.Information);
    }
}

The code gets the name of the file and the width and height that the smaller pieces should have, and loads the original image. It creates a Bitmap of the correct size and a Rectangle representing the area of that Bitmap. It then creates a Graphics object to work with the Bitmap.

Next the code figures out how many rows and columns of smaller images will fit completely within the original image and loops through the rows and columns.

For each row/column value, the code updates a Rectangle so it describes the area occupied by that piece of the image. It uses the Graphics object’s DrawImage method to copy the piece to the new Bitmap and saves the result in a bitmap file. I needed to use 24-bit bitmaps but you could change the second parameter in the Save method to save as a jpg, png, or some other format.


Download Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in graphics, image processing and tagged , , , , , , , , . Bookmark the permalink.

Leave a Reply

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