簡體   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