Skip to content

NullReferenceException in ImageSource.FromBinary despite valid byte array #480

@candinho87

Description

@candinho87

I'm experiencing a NullReferenceException when calling ImageSource.FromBinary() from PdfSharpCore, even though I'm providing a valid byte array. The exception occurs inside the PdfSharpCore library, not in my code.

Steps to Reproduce:

Generate a barcode image using SkiaSharp

Convert the image to PNG format and get byte array

Call ImageSource.FromBinary("filename.png", () => byteArray)

NullReferenceException is thrown within the PdfSharpCore library

Code Example:
`private ImageSource.IImageSource AddBarcode(string accessKey)
{
try
{
Console.WriteLine($"Generating barcode for: {accessKey}");

    var barCode = new Barcode();
    barCode.IncludeLabel = true;

    Console.WriteLine("Encoding image...");
    using SKImage image = barCode.Encode(BarcodeStandard.Type.Code128, accessKey, 350, 50);
    if (image == null)
    {
        throw new InvalidOperationException("Failed to encode image");
    }

    Console.WriteLine("Converting to PNG...");
    using SKData data = image.Encode(SKEncodedImageFormat.Png, 75);
    if (data == null)
    {
        throw new InvalidOperationException("Failed to convert to PNG");
    }

    byte[] imageData = data.ToArray();
    Console.WriteLine($"Array size: {imageData?.Length ?? 0} bytes");

    if (imageData == null || imageData.Length == 0)
    {
        throw new InvalidOperationException("Byte array is empty or null");
    }

    Console.WriteLine("Creating ImageSource...");
    var source = ImageSource.FromBinary("barcode.png", () => imageData);

    if (source == null)
    {
        throw new InvalidOperationException("ImageSource returned null");
    }

    Console.WriteLine("Successfully generated barcode");
    return source;
}
catch (Exception ex)
{
    Console.WriteLine($"ERROR: {ex.Message}");
    Console.WriteLine($"Stack: {ex.StackTrace}");
    
    return null;
}

}Error Stack Trace:System.NullReferenceException: Object reference not set to an instance of an object.
at MigraDocCore.DocumentObjectModel.MigraDoc.DocumentObjectModel.Shapes.ImageSource.FromBinary(String name, Func1 imageSource, Nullable1 quality)`
What I've Tried:

Verified the byte array is not null and contains data (confirmed with console output)

Used proper resource disposal with using statements

Tried different file extensions (.png, .jpg)

Confirmed SkiaSharp is generating valid image data (can save to file successfully)

Environment:

PdfSharpCore version: 1.3.65/1.3.67

MigraDocCore version: 1.3.65/1.3.67  

.NET version: Net9

OS: Windows

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions