PNM is a family of simple image formats designed to be easy to distribute, parse, and understand. It includes PBM for bitmap images, PGM for grayscale images, and PPM for color pixmaps; each has ASCII and binary encodings. section 12.1.1
A PNM header is always ASCII. Its magic number identifies both the image kind and encoding, followed by width and height; PGM and PPM also include a maximum sample value. Comments beginning with # may appear in the header, and the file extension is not the reliable format identifier. section 12.1.1
Table 12.1 Overview of the magic numbers for the PNM formats
|
Format
|
Magic numbers
|
Extension
|
Image data (for one pixel)
|
|
|---|---|---|---|---|
|
ASCII
|
Binary
|
|||
|
Portable bitmap format (PBM)
|
P1
|
P4
|
.pbm
|
0 (white) or
1 (black)
|
|
Portable graymap format (PGM)
|
P2
|
P5
|
.pgm
|
From
0 to
maximum value (grayscale), where the
maximum value is given in the header
|
|
Portable pixmap format (PPM)
|
P3
|
P6
|
.ppm
|
From
0 to
maximum value for each RGB channel, where the
maximum value is given in the header
|
Compare the six magic numbers, their usual extensions, and the pixel data represented by PBM, PGM, and PPM. section 12.1.1
Pixel representation depends on the magic number:
- P1 and P4 are bitmaps: each pixel is 0 or 1. P1 stores values as ASCII; P4 packs pixels as bits, read most-significant bit first. section 12.2.3
- P2 and P5 are graymaps: one value represents each pixel, limited by the header’s maximum value. section 12.1.1 section 12.2.3
- P3 and P6 are pixmaps: each pixel has red, green, and blue values, each limited by the header’s maximum value. section 12.1.1 section 12.2.3
- P4, P5, and P6 use binary data. Graymap and pixmap samples use one byte by default, or two bytes when the maximum value exceeds 255. section 12.2.3
A small ASCII bitmap
`P1` identifies an ASCII PBM image. The header gives a width and height of 2 by 2, while the four following values describe its black-and-white pixels. Header comments can sit alongside these fields. section 12.1.1
A complete PNM parser reads the header, selects data parsing from the magic number and maximum value, consumes the expected pixels, permits trailing whitespace, and rejects unconsumed input. Parsing alone yields raw data; separate validation checks pixel count, pixel shape, and maximum-value limits. section 12.2.4 section 13.1.1
