PDFsharp & MigraDoc Foundation
http://forum.pdfsharp.com/

Handled Exception in XImage.InitializeGdiHelper
http://forum.pdfsharp.com/viewtopic.php?f=3&t=2980
Page 1 of 1

Author:  ntiley [ Fri Nov 14, 2014 4:55 pm ]
Post subject:  Handled Exception in XImage.InitializeGdiHelper

Good afternoon

I noticed a handled exception today in my WPF project which was slowing down my batch PDF creation process. The exception occurs in PdfSharp.Drawing.XImage.InitializeGdiHelper when the XImage is initialised with a BitmapSource created from a MemoryStream. As there is no file on disk the line new System.Drawing.Bitmap(GetImageFilename(wpfImage)) throws an ArgumentException, this is handled silently but incurs a performance cost. The below illustrates the current workaround I have implemented to avoid this exception, I expect you'll prefer to determine the appropriate values for the isJpeg and isCmyk vars rather than skip this block of code completely but I'll include the workaround in case it is of any use

Code:
    private void InitializeGdiHelper()
    {
      if (!isCmyk.HasValue)
      {
        try
        {
            string imageFileName = GetImageFilename(wpfImage);
            if (!String.IsNullOrEmpty(imageFileName) && new System.IO.FileInfo(imageFileName).Exists)
            {
                using (System.Drawing.Image image = new System.Drawing.Bitmap(imageFileName))
                {
                    string guid = image.RawFormat.Guid.ToString("B").ToUpper();
                    isJpeg = guid == "{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}";
                    isCmyk = (image.Flags & ((int)System.Drawing.Imaging.ImageFlags.ColorSpaceCmyk | (int)System.Drawing.Imaging.ImageFlags.ColorSpaceYcck)) != 0;
                    if (isJpeg.Value)
                    {
                        memory = new MemoryStream();
                        image.Save(memory, System.Drawing.Imaging.ImageFormat.Jpeg);
                        if ((int)memory.Length == 0)
                        {
                            memory = null;
                        }
                    }
                }
            }
        }
        catch { }
      }
    }



Kind Regards, and thanks very much for all the work you've put into this excellent project
Nick

Author:  Thomas Hoevel [ Mon Nov 17, 2014 3:47 pm ]
Post subject:  Re: Handled Exception in XImage.InitializeGdiHelper

Hi, Nick,

Thanks for the feedback.

Is there any advantage in using "new System.IO.FileInfo(imageFileName).Exists" instead of "File.Exists(imageFilename)"?

Author:  ntiley [ Mon Nov 24, 2014 12:03 pm ]
Post subject:  Re: Handled Exception in XImage.InitializeGdiHelper

Hi Thomas

None whatsoever, that's the result of me making several edits to the code looking for a better fix and not reviewing it before submitting this item, File.Exists is more sensible


Nick

Page 1 of 1 All times are UTC
Powered by phpBB® Forum Software © phpBB Group
https://www.phpbb.com/