0

我有高度 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 个图像

4

1 回答 1

3

您应该考虑使用 for 循环而不是重复代码来重写您的代码。

像这样的东西:

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

还将位图包装using到释放文件句柄中。

于 2019-06-04T11:23:10.193 回答