0

Lets say I have 1 image Im looking for a way to have it in equal parts left from right I have this code however it cuts in long pieces:

var image = pictureBox1.Image;

        var splitInto = 12;

        using (var originalImage = new Bitmap(image))
        {
            for (int i = 0; i < splitInto; i++)
            {
                var rect = new Rectangle(0, originalImage.Height / splitInto * i, originalImage.Width, originalImage.Height / splitInto);
                using (var clonedImage = originalImage.Clone(rect, originalImage.PixelFormat))
                    clonedImage.Save(directory + $"\\PageImage{i + 1}.jpg");
            }
        }

Im looking for the result o look like this:

[ ] [ ] [ ] [ ]

[ ] [ ] [ ] [ ]

[ ] [ ] [ ] [ ]

Where each square is connecting piece to the image I thought about 2 for loops but i cant figure it out.

Original

Edited

1 Answers1

3

An image is a bidimentional object. You Don't say if your 12 pieces are 2 rows and 6 columns or 3 rows and 4 columns (or ...). So first of all, you should have 2 parameters; in your "like this" pattern, it seems you can set:

int splitX = 4;
int splitY = 3;

And, yes, it's much simpler and natural to have two nested loops than only one loop.

This is a possible solution:

  var image = pictureBox1.Image;
  var splitX = 4;
  var splitY = 3;

  using (var originalImage = new Bitmap(image))
  {
        var incX = originalImage.Width / splitX;
        var incY = originalImage.Height / splitY;
        var startX = 0;
        for (int i = 0; i < splitX; i++)
        {
            var startY = 0;
            for (int j = 0; j < splitY; j++)
            {
                var rect = new Rectangle(startX, startY, incX, incY);
                using (var clonedImage = originalImage.Clone(rect, originalImage.PixelFormat))
                    clonedImage.Save(directory + $"\\PageImage{i + 1}{j + 1}.jpg");
                startY += incY;
            }
            startX += incX;
        }
    }
Fredy
  • 532
  • 3
  • 11