Skip to content

XImage.FromStream swallows all PNG decode exceptions as "Unsupported image format." #366

@ltlombardi

Description

@ltlombardi

I don't think this will be easy to reproduce. But I though best to post here. I apologize if I'm wrong.

When XImage.FromStream is called with a PNG stream that fails to decode (e.g. due to OutOfMemoryException under memory pressure), the error is silently discarded and surfaced only as the generic InvalidOperationException: "Unsupported image format." This makes the root cause completely invisible in logs.

Root cause

In PngImageImporter, the entire import body is wrapped in a blanket catch(Exception){ return null; }. XImage.FromStream then sees a null result and throws the generic message, discarding the original exception.

This means an OutOfMemoryException caused by decoding a large PNG (e.g. 10800×7200 RGBA = ~300 MiB uncompressed pixel buffer) looks identical in logs to an unsupported file format — making the failure extremely difficult to diagnose in production.

Steps to reproduce

Attempt to convert a large PNG (e.g. 10800×7200 RGBA) to PDF using XImage.FromStream in a memory-constrained environment (kubernets pods with 1gb of ram or something like that)
Observe InvalidOperationException: "Unsupported image format." in the exception log
The actual cause (OutOfMemoryException) is nowhere to be found
Expected behavior

The original exception should be preserved, either as the thrown exception itself or as the InnerException, so callers can distinguish between "format not supported" and "decode failed due to memory/IO/corruption".

At minimum, OutOfMemoryException should not be caught — it is not recoverable and swallowing it can leave the process in an unstable state.

Suggested fix

Re-throw non-recoverable exceptions before the blanket catch, or wrap and preserve the original as InnerException:

catch (OutOfMemoryException) { throw; } // never swallow OOM
catch (Exception ex) { _lastException = ex; return null; } // preserve for caller
Environment

PDFsharp version: (6.2.3)

the image https://oo-prod.s3.amazonaws.com/public/artworks/resize/2025/09/08/bf218bcbb9954896/10800x7200.png

PdfSharpPdfGenerator.cs.txt

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions