Search code examples
c#asp.netimagehiqpdf

Split Image into n parts in c# and convert to pdf


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


Solution

  • 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.