How to split an image into smaller pieces in C#?
Asked Answered
G

2

7

How can I split an image into multiple sub images? Like, would I have to read the pixels and convert it to an image somehow?

For example:

If an image's dimension is 100px (width) and 180px (height) and I wanted to, say, split it as a 4x4, would I read the first 25px for the width and the first 45 px for the height and then just increment it correctly?

If so, what would I store the pixels to? More specifically, would it be saved as an array of bytes, images, etc?

Gabie answered 28/12, 2015 at 23:36 Comment(1)
Possible duplicate of Image splitting into 9 piecesDeci
S
5

You may try the following code sample (taken from https://stackoverflow.com/a/4118195/);

 for (int i = 0; i < 4; i++)
    {
        for (int y = 0; y < 4; y++)
        {
            Rectangle r = new Rectangle(i*(pictureBox1.Image.Width / 4), 
                                        y*(pictureBox1.Image.Height / 4), 
                                        pictureBox1.Image.Width / 4, 
                                        pictureBox1.Image.Height / 4);

            g.DrawRectangle(pen,r );

            list.Add(cropImage(pictureBox1.Image, r));
        }
    }

The other alternative is using BitMap.Clone, you may find an example in the following link.

Spontoon answered 28/12, 2015 at 23:40 Comment(1)
Please attribute your sources in future. Failure to do so is seen as plagiarism. See stackoverflow.com/help/referencingMessier
P
1

Use the Bitmap class to hold the image and its Clone method to cut out your rectangles of arbitrary size. As a Bitmap it comes with several convenience methods such as Save this overload will save to a stream another allows you to save it to a file.

Pork answered 28/12, 2015 at 23:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.