繁体   English   中英

将 tiff 文件转换为 pdf 时出现 C# 出 memory 异常

[英]C# out of memory exception when converting a tiff file to pdf

我有以下代码将多页 TIFF 转换为 PDF。 但我摆脱了 memory 问题,我不知道在哪里。

public void convertTifToPDF(string destinaton, string sourceFile)
        {
            try
            {
                PdfDocument doc = new PdfDocument();

                Image myimage = Image.FromFile(sourceFile);
                int numOfpages = myimage.GetFrameCount(FrameDimension.Page);

                for (int index = 0; index < numOfpages; index++)
                {
                    myimage.SelectActiveFrame(FrameDimension.Page, index);
                    MemoryStream strm = new MemoryStream();
                    myimage.Save(strm, System.Drawing.Imaging.ImageFormat.Tiff);
                    XImage ximg = XImage.FromStream(strm);
                    var page = new PdfPage();
                    page.Height = ximg.PointHeight;
                    page.Width = ximg.PointWidth;

                    doc.Pages.Add(page);
                    XGraphics xgr = XGraphics.FromPdfPage(doc.Pages[index]);
                    xgr.DrawImage(ximg, 0, 0);
                }
                doc.Save(destinaton + ".pdf");
                doc.Close();
                myimage.Dispose();
            }
            catch (Exception ex)
            {
                ErrorLog.LogError(ex, "Error in: convertTifToPDF");
            }
        }

我知道我需要处理一些对象,但是哪一个?

谢谢您的帮助!!!

正如@mxmissle 提到的,尝试将你的memoryStream 包装在“使用”中,这样它就可以在每个循环之后被释放。

   using(var strm = new MemoryStream())
   {
       myimage.Save(strm, System.Drawing.Imaging.ImageFormat.Tiff);
       XImage ximg = XImage.FromStream(strm);
       var page = new PdfPage();
       page.Height = ximg.PointHeight;
       page.Width = ximg.PointWidth;

       doc.Pages.Add(page);
       XGraphics xgr = XGraphics.FromPdfPage(doc.Pages[index]);
       xgr.DrawImage(ximg, 0, 0);
   }

使用 OptimizationOptions 删除未使用的对象。

                    var optimizOption = new Aspose.Pdf.Document.OptimizationOptions()

                    {
                        LinkDuplcateStreams = true,
                        RemoveUnusedObjects = true,
                        RemoveUnusedStreams = true,
                        CompressImages = true,
                        ImageQuality = 10
                    };

                    doc.OptimizeResources(optimizOption);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM