简体   繁体   中英

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

I have below code to convert multi-page TIFF to PDF. But I got out of memory issue and I do not know where.

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

I know I need to dispose some objects but which one?

Thanks for the help!!!

AS @mxmissle mentioned, try wrap your memoryStream in "using", so it can be disposed after each loop.

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

Use OptimizationOptions for removing unused objects.

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

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

                    doc.OptimizeResources(optimizOption);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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