← PNG
PNG·Format guide
All tools

How a PNG file is built

PNG (Portable Network Graphics, ISO/IEC 15948, W3C) stores a raster image losslessly: the pixels are filtered row by row and compressed with DEFLATE. Around them, the file is a sequence of self-describing chunks, so a reader can skip what it doesn't know. This page describes the layout as the PNG tool reads it, the variants found in mobile apps (Android 9-patches, Apple's CgBI), and the PngFile library.

Contents

  1. Signature and chunks
  2. Chunk types and their letters
  3. IHDR: the image header
  4. The other standard chunks
  5. Image data: filters and DEFLATE
  6. APNG animation
  7. Mobile variants: 9-patch and CgBI
  8. What to look for
  9. What the tool shows, and its limits
  10. The PngFile library
  11. The Inflate and Exif libraries

1Signature and chunks

Every PNG starts with the same 8 bytes, chosen to detect broken transfers: 89 50 4E 47 0D 0A 1A 0A — a byte with the high bit set (caught by 7-bit channels), “PNG”, a DOS line ending, Ctrl-Z (stops a DOS type), and a Unix line ending (caught by line-ending conversions).

Then chunks follow, until IEND. All numbers are big-endian.

Bytes Field Meaning
4 length The size of the data only (not of the type or CRC); at most 231−1.
4 type Four ASCII letters, such as IHDR.
length data What the chunk says; its layout depends on the type.
4 CRC CRC-32 of the type and data (the same CRC as ZIP), so damage is detected chunk by chunk.

The order matters: IHDR first; PLTE before the image data; the IDAT chunks consecutive; IEND last. Bytes after IEND are not part of the image. Decoders ignore them, which makes them a place to hide data.

2Chunk types and their letters

The case of each of the four letters is a flag (bit 5 of the byte):

Letter Uppercase Lowercase
1st critical: a decoder that doesn't know the chunk must refuse the image ancillary: it may be ignored
2nd public: defined by the specification or registered private: an application's own (Apple's iDOT, Android's npTc)
3rd always uppercase in valid files (reserved) —
4th unsafe to copy: it depends on the image; an editor that changes the pixels must drop it safe to copy: it survives edits

So IHDR is critical, public, unsafe to copy; tEXt ancillary, public, safe to copy.

3IHDR: the image header

Bytes Field Values
4 + 4 width, height In pixels, 1 to 231−1.
1 bit depth Bits per sample (or per palette index): 1, 2, 4, 8 or 16, depending on the colour type.
1 colour type 0 greyscale · 2 truecolour (RGB) · 3 indexed (palette) · 4 greyscale with alpha · 6 truecolour with alpha (RGBA). Bit 0 = palette, bit 1 = colour, bit 2 = alpha.
1 compression 0: DEFLATE (the only one).
1 filter method 0: adaptive filtering with the five row filters (the only one).
1 interlace 0 none · 1 Adam7.

4The other standard chunks

Type Contents
PLTE The palette: up to 256 RGB triples. Required for colour type 3, allowed (as a suggestion) for 2 and 6.
tRNS Transparency without an alpha channel: an alpha per palette entry, or one colour that is fully transparent.
gAMA · cHRM · sRGB · iCCP · cICP Colour space: gamma ×100000, primaries, the sRGB rendering intent, an embedded ICC profile (a name, then the zlib-compressed profile), or HDR code points.
tEXt · zTXt · iTXt Text: a keyword (Title, Author, Description, Software, Comment, XML:com.adobe.xmp…), a 0 byte, and Latin-1 text; zTXt compresses it; iTXt is UTF-8 with a language tag and a translated keyword, optionally compressed.
eXIf Exif metadata, a TIFF structure as in JPEG files (camera, dates, GPS position).
pHYs · tIME · bKGD · sBIT · hIST · sPLT Pixel size (pixels per metre, so 5669 = 144 dpi), last-modified time, background colour, significant bits, palette usage, suggested palettes.

5Image data: filters and DEFLATE

The pixels are packed row by row (samples of less than 8 bits share bytes, high bits first). Before compression, each row gets a filter byte and is replaced by its difference from a prediction, which compresses better:

Byte Filter Prediction for each byte
0 None 0 (the raw bytes)
1 Sub the byte one pixel to the left
2 Up the byte above
3 Average the floor of the mean of left and above
4 Paeth left, above or upper-left, whichever is closest to left + above − upper-left

The filtered rows are one zlib stream (a 2-byte header, DEFLATE data, an Adler-32 checksum), split over any number of IDAT chunks: the split carries no meaning. The inflated size must be exactly height × (1 + the row's byte length). With Adam7 interlacing the image is stored as 7 reduced images (passes over every 8th pixel, then the gaps), so a browser can show a coarse version early; each pass has its own rows and filter bytes.

6APNG animation

An animated PNG is a normal PNG for decoders that don't know animation (they show the default image), with three more chunks: acTL (the number of frames and of plays, 0 = forever) before the image data, an fcTL per frame (sequence number, size, position, delay as a fraction of a second, how to dispose of the frame and blend the next one), and fdAT chunks with the frames after the first (a sequence number, then data like IDAT's). When an fcTL comes before the IDAT, the default image is the first frame.

7Mobile variants: 9-patch and CgBI

Android 9-patch. A .9.png in the source tree has a 1-pixel border whose black pixels mark which columns and rows may stretch and where the content goes. aapt removes the border and stores what it said in private chunks: npTc (the stretchable x and y ranges, the content padding, and the colour of each region when it is a single colour, so drawing can skip it), npOl (outline insets, radius and alpha) and npLb (optical layout bounds). The tool decodes them; the APK holds the processed file.

Apple CgBI. Xcode's pngcrush rewrites the PNGs it copies into an iOS app: a CgBI chunk comes before IHDR, the image data is raw DEFLATE (no zlib header and checksum), the pixels are BGRA instead of RGBA, and the colours are premultiplied by alpha. Standard decoders reject these files or show wrong colours; tools that convert them back must undo all three changes. Apple also adds an iDOT chunk to many images, which splits the image data so two threads can decode halves; it isn't documented and the tool shows its numbers as they are.

8What to look for

9What the tool shows, and its limits

The overview (dimensions, colour, compression, problems, and a bar of how the file's bytes are used), every chunk with its fields decoded, CRC and bytes, the text, Exif and ICC metadata, the image data's compression ratio and row filters, and an APNG's frames. It doesn't decode or draw pixels, and doesn't check the Adler-32 checksum of the image data. For the bytes themselves, every chunk opens in the Hex tool.

10The PngFile library

lib/image/png.js is a JavaScript module with no user interface; it imports lib/compression/inflate.js and lib/image/exif.js.

import { PngFile } from "../../lib/image/png.js";
Member What it is
PngFile.parse(bytes, options) Reads a PNG from a Uint8Array; throws if the signature is wrong. options.inflateLimit: the most the image data may inflate to (64 MB).
PngFile.isPng(bytes) Whether the bytes start with the signature.
png.chunks [{ type, offset, length, dataOffset, crc, computedCrc, crcValid, properties: { critical, public, reservedBitSet, safeToCopy }, info, problems }]. info is the decoded chunk (for IHDR the header, for text chunks the text, for eXIf an Exif…), null for unknown types.
png.header IHDR: { width, height, bitDepth, colorType, colorTypeName, compression, filter, interlace, channels, bitsPerPixel, hasAlpha }.
png.texts The text chunks: [{ chunk, keyword, text, language, translatedKeyword, compressed }].
png.imageData { chunks, compressedSize, inflatedSize, expectedSize, filters: { None, Sub, Up, Average, Paeth }, zlib, error }.
png.apple · png.animation · png.trailing CgBI or not; { frames, plays } of an APNG; { offset, length } of data after IEND.
png.problems What is wrong with the file as a whole (order, missing chunks, CRCs, sizes).
png.data(chunk) The chunk's data bytes (a view into the file).
PngFile.CHUNK_NAMES · PngFile.COLOR_TYPES What each known chunk type is; the colour types with their channels and allowed depths.
const png = PngFile.parse(new Uint8Array(await file.arrayBuffer()));
console.log(png.header.width, png.header.height, png.header.colorTypeName);
for (const chunk of png.chunks) {
	console.log(chunk.type, chunk.length, chunk.crcValid ? "ok" : "bad CRC");
}
if (png.trailing) {
	console.log(png.trailing.length + " bytes after IEND");
}

11The Inflate and Exif libraries

lib/compression/inflate.js decompresses DEFLATE data synchronously (browsers' DecompressionStream is asynchronous); the PNG and PDF libraries use it. lib/image/exif.js reads Exif metadata, for the PNG and JPEG libraries. Neither has dependencies.

import { Inflate } from "../../lib/compression/inflate.js";
import { Exif } from "../../lib/image/exif.js";
Member What it is
Inflate.inflate(bytes, { format, limit, partial }) The decompressed bytes. format: "zlib", "raw" or "auto" (the default); limit: stop with an error past this many bytes (64 MB), against decompression bombs; partial: return what was decoded instead of throwing on damaged input.
Inflate.zlibHeader(bytes) { method, windowSize, level, dictionary }, or null when the bytes don't start with a zlib header.
Inflate.adler32(bytes) The Adler-32 checksum.
Exif.parse(bytes) Reads Exif from its TIFF header (II*\0 or MM\0*).
exif.directories [{ name, offset, entries, next }]: IFD0, Exif, GPS, Interoperability, IFD1. An entry is { tag, name, type, typeName, count, offset, value, text }.
exif.find(name) · exif.location() The first entry with a tag name; the GPS position { latitude, longitude, altitude } in degrees, or null.
exif.thumbnail · exif.littleEndian · exif.problems { offset, length } of the embedded JPEG thumbnail; the byte order; what couldn't be read.