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