在 C# 中将图像拆分为 n 个部分并转换为 pdf

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

我有高度 5262 和宽度 1240 的 png 图像需要将该图像拆分为 n 个部分,例如保存单个图像后 n = 3 需要将所有图像推送到单行本.pdf

需要水平分割图片并保存单张图片

        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"); 

拆分图像并将其转换为 pdf

问题:当我将它分成 3 个部分时,只创建了 2 个图像

您应该考虑 re-writing 您的代码使用 for-loop 而不是重复代码。

像这样:

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");
    }
}

还将 Bitmap 包装到 using 中以释放文件句柄。