{"record":{"id":"d55745fc3d0bff1e","repo":"SixLabors/ImageSharp","slug":"reached-eof-while-reading-the-header","errorCode":null,"errorMessage":"Reached EOF while reading the header.","messagePattern":"Reached EOF while reading the header\\.","errorType":"exception","errorClass":"InvalidImageContentException","httpStatus":null,"severity":"error","filePath":"src/ImageSharp/Formats/Pbm/PbmDecoderCore.cs","lineNumber":186,"sourceCode":"            }\n\n            stream.SkipWhitespaceAndComments();\n        }\n        else\n        {\n            this.componentType = PbmComponentType.Bit;\n        }\n\n        this.pixelSize = new Size(width, height);\n        this.Dimensions = this.pixelSize;\n        this.metadata = new ImageMetadata();\n        PbmMetadata meta = this.metadata.GetPbmMetadata();\n        meta.Encoding = this.encoding;\n        meta.ColorType = this.colorType;\n        meta.ComponentType = this.componentType;\n\n        [DoesNotReturn]\n        static void ThrowPrematureEof() => throw new InvalidImageContentException(\"Reached EOF while reading the header.\");\n    }\n\n    private void ProcessPixels<TPixel>(BufferedReadStream stream, Buffer2D<TPixel> pixels)\n        where TPixel : unmanaged, IPixel<TPixel>\n    {\n        if (this.encoding == PbmEncoding.Binary)\n        {\n            BinaryDecoder.Process(this.configuration, pixels, stream, this.colorType, this.componentType);\n        }\n        else\n        {\n            PlainDecoder.Process(this.configuration, pixels, stream, this.colorType, this.componentType);\n        }\n    }\n\n    private void ProcessUpscaling<TPixel>(Image<TPixel> image)\n        where TPixel : unmanaged, IPixel<TPixel>\n    {","sourceCodeStart":168,"sourceCodeEnd":204,"githubUrl":"https://github.com/SixLabors/ImageSharp/blob/59ce6af6fc29027cda277ef62d4d1694a8acce91/src/ImageSharp/Formats/Pbm/PbmDecoderCore.cs#L168-L204","documentation":"Thrown by PbmDecoderCore.ProcessHeader when the stream ends before a complete PNM header (magic, width, height, and for non-mono formats the max pixel value) has been read. The decoder needs the entire header before allocating the pixel buffer; premature EOF means the file is truncated or not a PNM image. Implemented via the local ThrowPrematureEof helper in PbmDecoderCore.cs:186.","triggerScenarios":"Image.Identify or Image.Load on a PNM stream that ends mid-header — e.g. a 0-byte or partially-written file, a stream that was not rewound, or a network source cut off after only the magic bytes.","commonSituations":"Truncated uploads/downloads, reading from a stream positioned after data was consumed, writing PNM files without flushing/closing the writer, or trying to decode a PNM still being produced by another process.","solutions":["Verify the source file/stream is fully written and complete (compare file size against the producer's expected output).","Re-download or re-export the image; the header bytes are unrecoverable.","For streams, reset the stream position to 0 before passing it to Image.Identify/Image.Load.","Check that the writer producing the file finished and disposed/flushed before the decoder reads it."],"exampleFix":"// before\nusing var stream = File.OpenRead(\"partial.pgm\");\nusing var image = Image.Load(stream);\n// after\nusing var stream = File.OpenRead(\"partial.pgm\");\nif (stream.Length < 10) // smallest sane PNM header is longer than this\n{\n    throw new IOException(\"PNM file is truncated; re-obtain the file.\");\n}\nstream.Position = 0;\nusing var image = Image.Load(stream);","handlingStrategy":"validation","validationCode":"// Ensure the stream holds at least a minimal complete PNM header before decoding\nif (!stream.CanSeek || stream.Length < 15)\n    throw new InvalidDataException(\"Source too short to contain a PNM header\");\nstream.Position = 0;","typeGuard":"static bool HasMinimalPnmHeader(Stream s)\n{\n    if (!s.CanSeek || s.Length < 15) return false;\n    Span<byte> buf = stackalloc byte[2];\n    s.Read(buf);\n    s.Position = 0;\n    return buf[0] == (byte)'P' && buf[1] is >= (byte)'1' and <= (byte)'7';\n}","tryCatchPattern":"try\n{\n    using var image = Image.Load(stream);\n}\ncatch (InvalidImageContentException ex) when (ex.Message.Contains(\"EOF while reading the header\"))\n{\n    throw new IOException(\"PNM source is truncated; re-obtain the file.\", ex);\n}","preventionTips":["Always flush/close writers before another process reads the PNM file.","Reset stream Position to 0 before decoding streams that were just read or written.","Check file sizes against producer expectations when receiving files over the network.","Use Image.Identify on suspicious inputs before full decode."],"tags":["pnm","image-decoding","truncated-file","eof"],"backgroundTag":"file-read-failed","analyzedSha":"59ce6af6fc29027cda277ef62d4d1694a8acce91","analyzedAt":"2026-09-13T18:34:59.331Z","contentChangedAt":"2026-09-13T18:34:59.331Z","schemaVersion":2},"datasetVersion":"2026-09-16T04:17:20.429Z"}