0

I have png image of Height 5262 and width 1240 need to split that image to n number of parts e.g n = 3 after saving individual image need to push all the images to single pdf.

Need to split image horizontally and save individual images

        var imgarray = new System.Drawing.Image[3]; 
        Bitmap imgsize = new Bitmap(path);
        var imageHeight = imgsize.Height;
        var imageWidth = imgsize.Width;
        string pathdata = Path.GetDirectoryName(path)
        Bitmap originalImage = new Bitmap(System.Drawing.Image.FromFile(path));
        System.Drawing.Rectangle rect = new System.Drawing.Rectangle(0, 0, originalImage.Width, (originalImage.Height / 3) + 1);

        Bitmap firstHalf = originalImage.Clone(rect, originalImage.PixelFormat);
        firstHalf.Save(pathdata+"\\PageImage1.jpg");
        rect = new System.Drawing.Rectangle(0, originalImage.Height / 3, originalImage.Width, originalImage.Height / 3);

        Bitmap secondHalf = originalImage.Clone(rect, originalImage.PixelFormat);
        secondHalf.Save(pathdata + "\\PageImage2.jpg");
        rect = new System.Drawing.Rectangle(0, originalImage.Height / 3, originalImage.Width, originalImage.Height / 3);
        Bitmap thirdHalf = originalImage.Clone(rect, originalImage.PixelFormat);
        thirdHalf.Save(pathdata+"\\PageImage3.jpg"); 

Split images and convert it to pdf

Issue : When i am splitting it to 3 parts only 2 images are getting created

Tony
  • 52
  • 15
  • 2
    Well your third half shouldn't be only `originalImage.Height / 3` but instead `originalImage.Height / 3 * 2` as you want to start from the 2nd 3th of the original height. – Rand Random Jun 04 '19 at 10:51
  • As you can see here, (preview in explorer) the code is working as expected after the change I mentioned in my earlier comment - https://i.stack.imgur.com/aKhvQ.png – Rand Random Jun 04 '19 at 11:14

1 Answers1

3

You should consider re-writing your code with a for-loop instead of duplicate code.

Something like this:

var path = Path.GetFullPath("07T0L.jpg");
string directory = Path.GetDirectoryName(path);

//optional: cleanup files from a previous run - incase the previous run splitted into 5 images and now we only produce 3, so that only 3 files will remain in the destination
var oldFiles = Directory.EnumerateFiles(directory, "PageImage*.jpg");
foreach (var oldFile in oldFiles)
    File.Delete(oldFile);

var splitInto = 3;
using (var img = Image.FromFile(path))
using (var originalImage = new Bitmap(img))
{
    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");
    }
}

Also wrapped the Bitmap into using to release file handles.

Rand Random
  • 7,300
  • 10
  • 40
  • 88