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

时间:2019-06-04 10:37:26

标签: c# asp.net image hiqpdf

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

2 个答案:

答案 0 :(得分: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中以释放文件句柄。

答案 1 :(得分:0)