W3C

Portable Network Graphics (PNG) Specification (Second Edition)
Information technology — Computer graphics and image processing — Portable Network Graphics (PNG): Functional specification. ISO/IEC 15948:2003 (E)

W3C Recommendation 10 November 2003

This version:
http://www.w3.org/TR/2003/REC-PNG-20031110
Latest version:
http://www.w3.org/TR/PNG
Previous version:
http://www.w3.org/TR/2003/PR-PNG-20030520
Editor:
David Duce, Oxford Brookes University (Second Edition)
Authors:
See author list

Please refer to the errata for this document, which may include some normative corrections.

See also the translations of this document.


Abstract

This document describes PNG (Portable Network Graphics), an extensible file format for the lossless, portable, well-compressed storage of raster images. PNG provides a patent-free replacement for GIF and can also replace many common uses of TIFF. Indexed-color, grayscale, and truecolor images are supported, plus an optional alpha channel. Sample depths range from 1 to 16 bits.

PNG is designed to work well in online viewing applications, such as the World Wide Web, so it is fully streamable with a progressive display option. PNG is robust, providing both full file integrity checking and simple detection of common transmission errors. Also, PNG can store gamma and chromaticity data for improved color matching on heterogeneous platforms.

This specification defines an Internet Media Type image/png.

Status of this document

This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.

This document is the 14 October 2003 W3C Recommendation of the PNG specification, second edition. It is also International Standard, ISO/IEC 15948:2003. The two documents have exactly identical content except for cover page and boilerplate differences as appropriate to the two organisations.

This International Standard is strongly based on the W3C Recommendation 'PNG Specification Version 1.0' which was reviewed by W3C members, approved as a W3C Recommendation and published in October 1996. This second edition incorporates all known errata and clarifications.

A complete review of the document has been done by ISO/IEC/JTC 1/SC 24 in collaboration with W3C and the PNG development group (the original authors of the PNG 1.0 Recommendation) in order to transform that Recommendation into an ISO/IEC international standard. A major design goal during this review was to avoid changes that will invalidate existing files, editors, or viewers that conform to W3C Recommendation PNG Specification Version 1.0.

The PNG specification enjoys a good level of implementation with good interoperability. At the time of this publication more than 180 image viewers could display PNG images and over 100 image editors could read and write valid PNG files. Full support of PNG is required for conforming SVG viewers; at the time of publication all eighteen SVG viewers had PNG support. HTML has no required image formats, but over 60 HTML browsers had at least basic support of PNG images.

Public comments on this W3C Recommendation are welcome. Please send them to the archived list png-group@w3.org .

The latest information regarding patent disclosures related to this document is available on the Web. As of this publication, the PNG Group are not aware of any royalty-bearing patents they believe to be essential to PNG.

This document has been produced by ISO/IEC JTC1 SC24 and the PNG Group as part of the Graphics Activity within the W3C Interaction Domain.

Note: To provide the highest quality images, this specification uses SVG diagrams with a PNG fallback using the HTML object element. SVG-enabled browsers will see the SVG figures with selectable text, other browsers will display the raster PNG version.

W3C is aware that there is a known incompatibility between the unsupported beta of Adobe SVG plugin for Linux and Mozilla versions greater than 0.9.9 due to changes in the plug-in API, causing a browser crash. Therefore, a normative PNG-only alternative version is available that does not use an object element. The two versions are otherwise identical.

Available languages

The English version of this specification is the only normative version. However, for translations in other languages see http://www.w3.org/Consortium/Translation/.

Table of Contents

Introduction

The design goals for this International Standard were:

  1. Portability: encoding, decoding, and transmission should be software and hardware platform independent.
  2. Completeness: it should be possible to represent truecolour, indexed-colour, and greyscale images, in each case with the option of transparency, colour space information, and ancillary information such as textual comments.
  3. Serial encode and decode: it should be possible for datastreams to be generated serially and read serially, allowing the datastream format to be used for on-the-fly generation and display of images across a serial communication channel.
  4. Progressive presentation: it should be possible to transmit datastreams so that an approximation of the whole image can be presented initially, and progressively enhanced as the datastream is received.
  5. Robustness to transmission errors: it should be possible to detect datastream transmission errors reliably.
  6. Losslessness: filtering and compression should preserve all information.
  7. Performance: any filtering, compression, and progressive image presentation should be aimed at efficient decoding and presentation. Fast encoding is a less important goal than fast decoding. Decoding speed may be achieved at the expense of encoding speed.
  8. Compression: images should be compressed effectively, consistent with the other design goals.
  9. Simplicity: developers should be able to implement the standard easily.
  10. Interchangeability: any standard-conforming PNG decoder shall be capable of reading all conforming PNG datastreams.
  11. Flexibility: future extensions and private additions should be allowed for without compromising the interchangeability of standard PNG datastreams.
  12. Freedom from legal restrictions: no algorithms should be used that are not freely available.

1 Scope

This International Standard specifies a datastream and an associated file format, Portable Network Graphics (PNG, pronounced "ping"), for a lossless, portable, compressed individual computer graphics image transmitted across the Internet. Indexed-colour, greyscale, and truecolour images are supported, with optional transparency. Sample depths range from 1 to 16 bits. PNG is fully streamable with a progressive display option. It is robust, providing both full file integrity checking and simple detection of common transmission errors. PNG can store gamma and chromaticity data as well as a full ICC colour profile for accurate colour matching on heterogenous platforms. This Standard defines the Internet Media type "image/png". The datastream and associated file format have value outside of the main design goal.

2 Normative references

The following normative documents contain provisions which, through reference in this text, constitute provisions of this International Standard. For dated references, subsequent amendments to, or revisions of, any of these publications do not apply. However, parties to agreements based on this International Standard are encouraged to investigate the possibility of applying the most recent editions of the normative documents indicated below. For undated references, the latest edition of the normative document referred to applies. Members of ISO and IEC maintain registers of currently valid International Standards.

ISO 639:1988, Code for the representation of names of languages.

ISO/IEC 646:1991, International Organization for Standardization, Information technology — ISO 7-bit coded character set for information interchange.

ISO/IEC 3309:1993, Information Technology — Telecommunications and information exchange between systems — High-level data link control (HDLC) procedures — Frame structure.

ISO/IEC 8859-1:1998, Information technology — 8-bit single-byte coded graphic character sets — Part 1: Latin alphabet No. 1.
For convenience, here is a non-normative sample text file describing the codes and associated character names.

ISO/IEC 9899:1990(R1997), Programming languages — C.

ISO/IEC 10646-1:1993/AMD.2, Information technology — Universal Multiple-Octet Coded Character Sets (UCS) — Part 1: Architecture and Basic Multilingual Plane.

IEC 61966-2-1, Multimedia systems and equipment — Colour measurement and management — Part 2-1: Default RGB colour space — sRGB, available at http://www.iec.ch/.

CIE-15.2, CIE, "Colorimetry, Second Edition". CIE Publication 15.2-1986. ISBN 3-900-734-00-3.

ICC-1, International Color Consortium, "Specification ICC.1: 1998-09, File Format for Color Profiles", 1998, available at http://www.color.org/

ICC-1A, International Color Consortium, "Specification ICC.1A: 1999-04, Addendum 2 to ICC.1: 1998-09", 1999, available at http://www.color.org/

RFC-1123, Braden, R., Editor, "Requirements for Internet Hosts — Application and Support", STD 3, RFC 1123, USC/Information Sciences Institute, October 1989.
http://www.ietf.org/rfc/rfc1123.txt

RFC-1950, Deutsch, P. and Gailly, J-L., "ZLIB Compressed Data Format Specification version 3.3", RFC 1950, Aladdin Enterprises, May 1996.
http://www.ietf.org/rfc/rfc1950.txt

RFC-1951, Deutsch, P., "DEFLATE Compressed Data Format Specification version 1.3", RFC 1951, Aladdin Enterprises, May 1996.
http://www.ietf.org/rfc/rfc1951.txt

RFC-2045, Freed, N. and Borenstein, N. , "MIME (Multipurpose Internet Mail Extensions) Part One: Format of Internet Message Bodies", RFC 2045, Innosoft, First Virtual, November 1996.
http://www.ietf.org/rfc/rfc2045.txt

RFC-2048, Freed, N., Klensin, J. and Postel, J., "Multipurpose Internet Mail Extensions (MIME) Part Four: Registration Procedures", RFC 2048, Innosoft, MCI, ISI, November 1996.
http://www.ietf.org/rfc/rfc2048.txt

RFC-3066, Alvestrand, H., "Tags for the Identification of Languages", RFC 3066, Cisco Systems, January 2001. (Obsoletes RFC 1766.)
http://www.ietf.org/rfc/rfc3066.txt

3 Terms, definitions, and abbreviated terms

3.1 Definitions

For the purposes of this International Standard the following definitions apply.

3.1.1 alpha
a value representing a pixel's degree of opacity. The more opaque a pixel, the more it hides the background against which the image is presented. Zero alpha represents a completely transparent pixel, maximum alpha represents a completely opaque pixel.
3.1.2 alpha compaction
an implicit representation of transparent pixels. If every pixel with a specific colour or greyscale value is fully transparent and all other pixels are fully opaque, the alpha channel may be represented implicitly.
3.1.3 alpha separation
separating an alpha channel in which every pixel is fully opaque; all alpha values are the maximum value. The fact that all pixels are fully opaque is represented implicitly.
3.1.4 alpha table
indexed table of alpha sample values, which in an indexed-colour image defines the alpha sample values of the reference image. The alpha table has the same number of entries as the palette.
3.1.5 ancillary chunk
class of chunk that provides additional information. A PNG decoder, without processing an ancillary chunk, can still produce a meaningful image, though not necessarily the best possible image.
3.1.6 bit depth
for indexed-colour images, the number of bits per palette index. For other images, the number of bits per sample in the image. This is the value that appears in the IHDR chunk.
3.1.7 byte
8 bits; also called an octet. The highest bit (value 128) of a byte is numbered bit 7; the lowest bit (value 1) is numbered bit 0.
3.1.8 byte order
ordering of bytes for multi-byte data values within a PNG file or PNG datastream. PNG uses network byte order.
3.1.9 channel
array of all per-pixel information of a particular kind within a reference image. There are five kinds of information: red, green, blue, greyscale, and alpha. For example the alpha channel is the array of alpha values within a reference image.
3.1.10 chromaticity (CIE)
pair of values x,y that precisely specify a colour, except for the brightness information.
3.1.11 chunk
section of a PNG datastream. Each chunk has a chunk type. Most chunks also include data. The format and meaning of the data within the chunk are determined by the chunk type. Each chunk is either a critical chunk or an ancillary chunk.
3.1.12 colour type
value denoting how colour and alpha are specified in the PNG image. Colour types are sums of the following values: 1 (palette used), 2 (truecolour used), 4 (alpha used). The permitted values of colour type are 0, 2, 3, 4, and 6.
3.1.13 composite (verb)
to form an image by merging a foreground image and a background image, using transparency information to determine where and to what extent the background should be visible. The foreground image is said to be "composited against" the background.
3.1.14 critical chunk
chunk that shall be understood and processed by the decoder in order to produce a meaningful image from a PNG datastream.
3.1.15 datastream
sequence of bytes. This term is used rather than "file" to describe a byte sequence that may be only a portion of a file. It is also used to emphasize that the sequence of bytes might be generated and consumed "on the fly", never appearing in a stored file at all.
3.1.16 deflate
name of a particular compression algorithm. This algorithm is used, in compression mode 0, in conforming PNG datastreams. Deflate is a member of the LZ77 family of compression methods. It is defined in [RFC-1951].
3.1.17 delivered image
image constructed from a decoded PNG datastream.
3.1.18 filter
transformation applied to an array of scanlines with the aim of improving their compressibility. PNG uses only lossless (reversible) filter algorithms.
3.1.19 frame buffer
the final digital storage area for the image shown by most types of computer display. Software causes an image to appear on screen by loading the image into the frame buffer.
3.1.20 gamma
exponent that describes approximations to certain non-linear transfer functions encountered in image capture and reproduction. Within this International Standard, gamma is the exponent in the transfer function from display_output to image_sample
image_sample = display_outputgamma
where both display_output and image_sample are scaled to the range 0 to 1.
3.1.21 greyscale
image representation in which each pixel is defined by a single sample of colour information, representing overall luminance (on a scale from black to white), and optionally an alpha sample (in which case it is called greyscale with alpha).
3.1.22 image data
1-dimensional array of scanlines within an image.
3.1.23 indexed-colour
image representation in which each pixel of the original image is represented by a single index into a palette. The selected palette entry defines the actual colour of the pixel.
3.1.24 indexing
representing an image by a palette, an alpha table, and an array of indices pointing to entries in the palette and alpha table.
3.1.25 interlaced PNG image
sequence of reduced images generated from the PNG image by pass extraction.
3.1.26 lossless compression
method of data compression that permits reconstruction of the original data exactly, bit-for-bit.
3.1.27 lossy compression
method of data compression that permits reconstruction of the original data approximately, rather than exactly.
3.1.28 luminance
formal definition of luminance is in [CIE-15.2]. Informally it is the perceived brightness, or greyscale level, of a colour. Luminance and chromaticity together fully define a perceived colour.
3.1.29 LZ77
data compression algorithm described by Ziv and Lempel in their 1977 paper [ZL].
3.1.30 network byte order
byte order in which the most significant byte comes first, then the less significant bytes in descending order of significance (MSB LSB for two-byte integers, MSB B2 B1 LSB for four-byte integers).
3.1.31 palette
indexed table of three 8-bit sample values, red, green, and blue, which with an indexed-colour image defines the red, green, and blue sample values of the reference image. In other cases, the palette may be a suggested palette that viewers may use to present the image on indexed-colour display hardware. Alpha samples may be defined for palette entries via the alpha table and may be used to reconstruct the alpha sample values of the reference image.
3.1.32 pass extraction
organizing a PNG image as a sequence of reduced images to change the order of transmission and enable progressive display.
3.1.33 pixel
information stored for a single grid point in an image. A pixel consists of (or points to) a sequence of samples from all channels. The complete image is a rectangular array of pixels.
3.1.34 PNG datastream
result of encoding a PNG image. A PNG datastream consists of a PNG signature followed by a sequence of chunks.
3.1.35 PNG decoder
process or device which reconstructs the reference image from a PNG datastream and generates a corresponding delivered image.
3.1.36 PNG editor
process or device which creates a modification of an existing PNG datastream, preserving unmodified ancillary information wherever possible, and obeying the chunk ordering rules, even for unknown chunk types.
3.1.37 PNG encoder
process or device which constructs a reference image from a source image, and generates a PNG datastream representing the reference image.
3.1.38 PNG file
PNG datastream stored as a file.
3.1.39 PNG four-byte signed integer
a four-byte signed integer limited to the range -(231-1) to 231-1. The restriction is imposed in order to accommodate languages that have difficulty with the value -231.
3.1.40 PNG four-byte unsigned integer
a four-byte unsigned integer limited to the range 0 to 231-1. The restriction is imposed in order to accommodate languages that have difficulty with unsigned four-byte values.
3.1.41 PNG image
result of transformations applied by a PNG encoder to a reference image, in preparation for encoding as a PNG datastream, and the result of decoding a PNG datastream.
3.1.42 PNG signature
sequence of bytes appearing at the start of every PNG datastream. It differentiates a PNG datastream from other types of datastream and allows early detection of some transmission errors.
3.1.43 reduced image
pass of the interlaced PNG image extracted from the PNG image by pass extraction.
3.1.44 reference image
rectangular array of rectangular pixels, each having the same number of samples, either three (red, green, blue) or four (red, green, blue, alpha). Every reference image can be represented exactly by a PNG datastream and every PNG datastream can be converted into a reference image. Each channel has a sample depth in the range 1 to 16. All samples in the same channel have the same sample depth. Different channels may have different sample depths.
3.1.45 RGB merging
converting an image in which the red, green, and blue samples for each pixel have the same value, and the same sample depth, into an image with a single greyscale channel.
3.1.46 sample
intersection of a channel and a pixel in an image.
3.1.47 sample depth
number of bits used to represent a sample value. In an indexed-colour PNG image, samples are stored in the palette and thus the sample depth is always 8 by definition of the palette. In other types of PNG image it is the same as the bit depth.
3.1.48 sample depth scaling
mapping of a range of sample values onto the full range of a sample depth allowed in a PNG image.
3.1.49 scanline
row of pixels within an image or interlaced PNG image.
3.1.50 source image
image which is presented to a PNG encoder.
3.1.51 truecolour
image representation in which each pixel is defined by samples, representing red, green, and blue intensities and optionally an alpha sample (in which case it is referred to as truecolour with alpha).
3.1.52 white point
chromaticity of a computer display's nominal white value.
3.1.53 zlib
particular format for data that have been compressed using deflate-style compression. Also the name of a library containing a sample implementation of this method. The format is defined in [RFC-1950].

3.2 Abbreviated terms

3.2.1 CRC
Cyclic Redundancy Code. A CRC is a type of check value designed to detect most transmission errors. A decoder calculates the CRC for the received data and checks by comparing it to the CRC calculated by the encoder and appended to the data. A mismatch indicates that the data or the CRC were corrupted in transit.
3.2.2 CRT
Cathode Ray Tube: a common type of computer display hardware.
3.2.2 LSB
Least Significant Byte of a multi-byte value.
3.2.3 LUT
Look Up Table. In frame buffer hardware, a LUT can be used to map indexed-colour pixels into a selected set of truecolour values, or to perform gamma correction. In software, a LUT can often be used as a fast way of implementing any mathematical function of a single integer variable.
3.2.4 MSB
Most Significant Byte of a multi-byte value.

4 Concepts

4.1 Images

This International Standard specifies the PNG datastream, and places some requirements on PNG encoders, which generate PNG datastreams, PNG decoders, which interpret PNG datastreams, and PNG editors, which transform one PNG datastream into another. It does not specify the interface between an application and either a PNG encoder, decoder, or editor. The precise form in which an image is presented to an encoder or delivered by a decoder is not specified. Four kinds of image are distinguished.

  1. The source image is the image presented to a PNG encoder.
  2. The reference image, which only exists conceptually, is a rectangular array of rectangular pixels, all having the same width and height, and all containing the same number of unsigned integer samples, either three (red, green, blue) or four (red, green, blue, alpha). The array of all samples of a particular kind (red, green, blue, or alpha) is called a channel. Each channel has a sample depth in the range 1 to 16, which is the number of bits used by every sample in the channel. Different channels may have different sample depths. The red, green, and blue samples determine the intensities of the red, green, and blue components of the pixel's colour; if they are all zero, the pixel is black, and if they all have their maximum values (2sampledepth-1), the pixel is white. The alpha sample determines a pixel's degree of opacity, where zero means fully transparent and the maximum value means fully opaque. In a three-channel reference image all pixels are fully opaque. (It is also possible for a four-channel reference image to have all pixels fully opaque; the difference is that the latter has a specific alpha sample depth, whereas the former does not.) Each horizontal row of pixels is called a scanline. Pixels are ordered from left to right within each scanline, and scanlines are ordered from top to bottom. A PNG encoder may transform the source image directly into a PNG image, but conceptually it first transforms the source image into a reference image, then transforms the reference image into a PNG image. Depending on the type of source image, the transformation from the source image to a reference image may require the loss of information. That transformation is beyond the scope of this International Standard. The reference image, however, can always be recovered exactly from a PNG datastream.
  3. The PNG image is obtained from the reference image by a series of transformations: alpha separation, indexing, RGB merging, alpha compaction, and sample depth scaling. Five types of PNG image are defined (see 6.1: Colour types and values). (If the PNG encoder actually transforms the source image directly into the PNG image, and the source image format is already similar to the PNG image format, the encoder may be able to avoid doing some of these transformations.) Although not all sample depths in the range 1 to 16 bits are explicitly supported in the PNG image, the number of significant bits in each channel of the reference image may be recorded. All channels in the PNG image have the same sample depth. A PNG encoder generates a PNG datastream from the PNG image. A PNG decoder takes the PNG datastream and recreates the PNG image.
  4. The delivered image is constructed from the PNG image obtained by decoding a PNG datastream. No specific format is specified for the delivered image. A viewer presents an image to the user as close to the appearance of the original source image as it can achieve.

The relationships between the four kinds of image are illustrated in figure 4.1.

Figure 4.1: Relationships between
source, reference, PNG, and display images

Figure 4.1 — Relationships between source, reference, PNG, and display images

The relationships between samples, channels, pixels, and sample depth are illustrated in figure 4.2.

Figure 4.2: Relationships between
sample, sample depth, pixel, and channel

Figure 4.2 — Relationships between sample, sample depth, pixel, and channel

4.2 Colour spaces

The RGB colour space in which colour samples are situated may be specified in one of three ways:

  1. by an ICC profile;
  2. by specifying explicitly that the colour space is sRGB when the samples conform to this colour space;
  3. by specifying the value of gamma and the 1931 CIE x,y chromaticities of the red, green, and blue primaries used in the image and the reference white point.

For high-end applications the first method provides the most flexibility and control. The second method enables one particular colour space to be indicated. The third method enables the exact chromaticities of the RGB data to be specified, along with the gamma correction (the power function relating the desired display output with the image samples) to be applied (see Annex C: Gamma and chromaticity). It is recommended that explicit gamma information also be provided when either the first or second method is used, for use by PNG decoders that do not support full ICC profiles or the sRGB colour space. Such PNG decoders can still make sensible use of gamma information. PNG decoders are strongly encouraged to use this information, plus information about the display system, in order to present the image to the viewer in a way that reproduces as closely as possible what the image's original author saw .

Gamma correction is not applied to the alpha channel, if present. Alpha samples always represent a linear fraction of full opacity.

4.3 Reference image to PNG image transformation

4.3.1 Introduction

A number of transformations are applied to the reference image to create the PNG image to be encoded (see figure 4.3). The transformations are applied in the following sequence, where square brackets mean the transformation is optional:

        [alpha separation]
        indexing or ( [RGB merging] [alpha compaction] )
        sample depth scaling

When every pixel is either fully transparent or fully opaque, the alpha separation, alpha compaction, and indexing transformations can cause the recovered reference image to have an alpha sample depth different from the original reference image, or to have no alpha channel. This has no effect on the degree of opacity of any pixel. The two reference images are considered equivalent, and the transformations are considered lossless. Encoders that nevertheless wish to preserve the alpha sample depth may elect not to perform transformations that would alter the alpha sample depth.

Figure 4.3: Reference image to PNG
image transformation

Figure 4.3 — Reference image to PNG image transformation

4.3.2 Alpha separation

If all alpha samples in a reference image have the maximum value, then the alpha channel may be omitted, resulting in an equivalent image that can be encoded more compactly.

4.3.3 Indexing

If the number of distinct pixel values is 256 or less, and the RGB sample depths are not greater than 8, and the alpha channel is absent or exactly 8 bits deep or every pixel is either fully transparent or fully opaque, then an alternative representation called indexed-colour may be more efficient for encoding. Each pixel is replaced by an index into a palette. The palette is a list of entries each containing three 8-bit samples (red, green, blue). If an alpha channel is present, there is also a parallel table of 8-bit alpha samples.

Figure 4.4: Indexed-colour
image

Figure 4.4 — Indexed-colour image

A suggested palette or palettes may be constructed even when the PNG image is not indexed-colour in order to assist viewers that are capable of displaying only a limited number of colours.

For indexed-colour images, encoders can rearrange the palette so that the table entries with the maximum alpha value are grouped at the end. In this case the table can be encoded in a shortened form that does not include these entries.

4.3.4 RGB merging

If the red, green, and blue channels have the same sample depth, and for each pixel the values of the red, green, and blue samples are equal, then these three channels may be merged into a single greyscale channel.

4.3.5 Alpha compaction

For non-indexed images, if there exists an RGB (or greyscale) value such that all pixels with that value are fully transparent while all other pixels are fully opaque, then the alpha channel can be represented more compactly by merely identifying the RGB (or greyscale) value that is transparent.

4.3.6 Sample depth scaling

In the PNG image, not all sample depths are supported (see 6.1: Colour types and values), and all channels shall have the same sample depth. All channels of the PNG image use the smallest allowable sample depth that is not less than any sample depth in the reference image, and the possible sample values in the reference image are linearly mapped into the next allowable range for the PNG image. Figure 4.5 shows how samples of depth 3 might be mapped into samples of depth 4.

Figure 4.5: Scaling sample
values

Figure 4.5 — Scaling sample values

Allowing only a few sample depths reduces the number of cases that decoders have to cope with. Sample depth scaling is reversible with no loss of data, because the reference image sample depths can be recorded in the PNG datastream. In the absence of recorded sample depths, the reference image sample depth equals the PNG image sample depth. See 12.5: Sample depth scaling and 13.12: Sample depth rescaling.

Figure 4.6: Possible PNG image
pixel types

Figure 4.6 — Possible PNG image pixel types

4.4 PNG image

The transformation of the reference image results in one of five types of PNG image (see figure 4.6) :

  1. Truecolour with alpha: each pixel consists of four samples: red, green, blue, and alpha.
  2. Greyscale with alpha: each pixel consists of two samples: grey and alpha.
  3. Truecolour: each pixel consists of three samples: red, green, and blue. The alpha channel may be represented by a single pixel value. Matching pixels are fully transparent, and all others are fully opaque. If the alpha channel is not represented in this way, all pixels are fully opaque.
  4. Greyscale: each pixel consists of a single sample: grey. The alpha channel may be represented by a single pixel value as in the previous case. If the alpha channel is not represented in this way, all pixels are fully opaque.
  5. Indexed-colour: each pixel consists of an index into a palette (and into an associated table of alpha values, if present).

The format of each pixel depends on the PNG image type and the bit depth. For PNG image types other than indexed-colour, the bit depth specifies the number of bits per sample, not the total number of bits per pixel. For indexed-colour images, the bit depth specifies the number of bits in each palette index, not the sample depth of the colours in the palette or alpha table. Within the pixel the samples appear in the following order, depending on the PNG image type.

  1. Truecolour with alpha: red, green, blue, alpha.
  2. Greyscale with alpha: grey, alpha.
  3. Truecolour: red, green, blue.
  4. Greyscale: grey.
  5. Indexed-colour: palette index.

4.5 Encoding the PNG image

4.5.1 Introduction

A conceptual model of the process of encoding a PNG image is given in figure 4.7. The steps refer to the operations on the array of pixels or indices in the PNG image. The palette and alpha table are not encoded in this way.

  1. Pass extraction: to allow for progressive display, the PNG image pixels can be rearranged to form several smaller images called reduced images or passes.
  2. Scanline serialization: the image is serialized a scanline at a time. Pixels are ordered left to right in a scanline and scanlines are ordered top to bottom.
  3. Filtering: each scanline is transformed into a filtered scanline using one of the defined filter types to prepare the scanline for image compression.
  4. Compression: occurs on all the filtered scanlines in the image.
  5. Chunking: the compressed image is divided into conveniently sized chunks. An error detection code is added to each chunk.
  6. Datastream construction: the chunks are inserted into the datastream.

4.5.2 Pass extraction

Pass extraction (see figure 4.8) splits a PNG image into a sequence of reduced images where the first image defines a coarse view and subsequent images enhance this coarse view until the last image completes the PNG image. The set of reduced images is also called an interlaced PNG image. Two interlace methods are defined in this International Standard. The first method is a null method; pixels are stored sequentially from left to right and scanlines from top to bottom. The second method makes multiple scans over the image to produce a sequence of seven reduced images. The seven passes for a sample image are illustrated in figure 4.8. See clause 8: Interlacing and pass extraction.

Figure 4.7: Encoding the PNG
image

Figure 4.7 — Encoding the PNG image

Figure 4.8: Pass extraction

Figure 4.8 — Pass extraction

4.5.3 Scanline serialization

Each row of pixels, called a scanline, is represented as a sequence of bytes.

4.5.4 Filtering

PNG standardizes one filter method and several filter types that may be used to prepare image data for compression. It transforms the byte sequence in a scanline to an equal length sequence of bytes preceded by a filter type byte (see figure 4.9 for an example). The filter type byte defines the specific filtering to be applied to a specific scanline. The encoder shall use only a single filter method for an interlaced PNG image, but may use different filter types for each scanline in a reduced image. See clause 9: Filtering.

Figure 4.9: Serializing and
filtering a scanline

Figure 4.9 — Serializing and filtering a scanline

4.5.5 Compression

The sequence of filtered scanlines in the pass or passes of the PNG image is compressed (see figure 4.10) by one of the defined compression methods. The concatenated filtered scanlines form the input to the compression stage. The output from the compression stage is a single compressed datastream. See clause 10: Compression.

4.5.6 Chunking

Chunking provides a convenient breakdown of the compressed datastream into manageable chunks (see figure 4.10). Each chunk has its own redundancy check. See clause 11: Chunk specifications.

Figure 4.10: Compression

Figure 4.10 — Compression

4.6 Additional information

Ancillary information may be associated with an image. Decoders may ignore all or some of the ancillary information. The types of ancillary information provided are described in Table 4.1.

Table 4.1 — Types of ancillary information
Type of information Description
Background colour Solid background colour to be used when presenting the image if no better option is available.
Gamma and chromaticity Gamma characteristic of the image with respect to the desired output intensity, and chromaticity characteristics of the RGB values used in the image.
ICC profile Description of the colour space (in the form of an International Color Consortium (ICC) profile) to which the samples in the image conform.
Image histogram Estimates of how frequently the image uses each palette entry.
Physical pixel dimensions Intended pixel size and aspect ratio to be used in presenting the PNG image.
Significant bits The number of bits that are significant in the samples.
sRGB colour space A rendering intent (as defined by the International Color Consortium) and an indication that the image samples conform to this colour space.
Suggested palette A reduced palette that may be used when the display device is not capable of displaying the full range of colours in the image.
Textual data Textual information (which may be compressed) associated with the image.
Time The time when the PNG image was last modified.
Transparency Alpha information that allows the reference image to be reconstructed when the alpha channel is not retained in the PNG image.

4.7 PNG datastream

4.7.1 Chunks

The PNG datastream consists of a PNG signature (see 5.2: PNG signature) followed by a sequence of chunks (see clause 11: Chunk specifications). Each chunk has a chunk type which specifies its function.

4.7.2 Chunk types

There are 18 chunk types defined in this International Standard. Chunk types are four-byte sequences chosen so that they correspond to readable labels when interpreted in the ISO 646.IRV:1991 character set. The first four are termed critical chunks, which shall be understood and correctly interpreted according to the provisions of this International Standard. These are:

  1. IHDR: image header, which is the first chunk in a PNG datastream.
  2. PLTE: palette table associated with indexed PNG images.
  3. IDAT: image data chunks.
  4. IEND: image trailer, which is the last chunk in a PNG datastream.

The remaining 14 chunk types are termed ancillary chunk types, which encoders may generate and decoders may interpret.

  1. Transparency information: tRNS (see 11.3.2: Transparency information).
  2. Colour space information: cHRM, gAMA, iCCP, sBIT, sRGB (see 11.3.3: Colour space information).
  3. Textual information: iTXt, tEXt, zTXt (see 11.3.4: Textual information).
  4. Miscellaneous information: bKGD, hIST, pHYs, sPLT (see 11.3.5: Miscellaneous information).
  5. Time information: tIME (see 11.3.6: Time stamp information).

4.8 Error handling

Errors in a PNG datastream fall into two general classes:

  1. transmission errors or damage to a computer file system, which tend to corrupt much or all of the datastream;
  2. syntax errors, which appear as invalid values in chunks, or as missing or misplaced chunks. Syntax errors can be caused not only by encoding mistakes, but also by the use of registered or private values, if those values are unknown to the decoder.

PNG decoders should detect errors as early as possible, recover from errors whenever possible, and fail gracefully otherwise. The error handling philosophy is described in detail in 13.2: Error handling.

4.9 Extension and registration

For some facilities in PNG, there are a number of alternatives defined, and this International Standard allows other alternatives to be defined by registration. According to the rules for the designation and operation of registration authorities in the ISO/IEC Directives, the ISO and IEC Councils have designated the following as the registration authority:

The World-Wide Web Consortium Host at ERCIM
The Registration Authority for PNG
INRIA- Sophia Antipolis
BP 93
06902 Sophia Antipolis Cedex
FRANCE
Email:png-group@w3.org

To ensure timely processing the Registration Authority should be contacted by email.

The following entities may be registered:

  1. chunk type;
  2. text keyword.

The following entities are reserved for future standardization:

  1. undefined field values less than 128;
  2. filter method;
  3. filter type;
  4. interlace method;
  5. compression method.

5 Datastream structure

5.1 Introduction

This clause defines the PNG signature and the basic properties of chunks. Individual chunk types are discussed in clause 11: Chunk specifications.

5.2 PNG signature

The first eight bytes of a PNG datastream always contain the following (decimal) values:

   137 80 78 71 13 10 26 10

This signature indicates that the remainder of the datastream contains a single PNG image, consisting of a series of chunks beginning with an IHDR chunk and ending with an IEND chunk.

5.3 Chunk layout

Each chunk consists of three or four fields (see figure 5.1). The meaning of the fields is described in Table 5.1. The chunk data field may be empty.

Figure 5.1: Chunk parts

Figure 5.1 — Chunk parts

Table 5.1 — Chunk fields
Length A four-byte unsigned integer giving the number of bytes in the chunk's data field. The length counts only the data field, not itself, the chunk type, or the CRC. Zero is a valid length. Although encoders and decoders should treat the length as unsigned, its value shall not exceed 231-1 bytes.
Chunk Type A sequence of four bytes defining the chunk type. Each byte of a chunk type is restricted to the decimal values 65 to 90 and 97 to 122. These correspond to the uppercase and lowercase ISO 646 letters (A-Z and a-z) respectively for convenience in description and examination of PNG datastreams. Encoders and decoders shall treat the chunk types as fixed binary values, not character strings. For example, it would not be correct to represent the chunk type IDAT by the equivalents of those letters in the UCS 2 character set. Additional naming conventions for chunk types are discussed in 5.4: Chunk naming conventions.
Chunk Data The data bytes appropriate to the chunk type, if any. This field can be of zero length.
CRC A four-byte CRC (Cyclic Redundancy Code) calculated on the preceding bytes in the chunk, including the chunk type field and chunk data fields, but not including the length field. The CRC can be used to check for corruption of the data. The CRC is always present, even for chunks containing no data. See 5.5: Cyclic Redundancy Code algorithm.

The chunk data length may be any number of bytes up to the maximum; therefore, implementors cannot assume that chunks are aligned on any boundaries larger than bytes.

5.4 Chunk naming conventions

Chunk types are chosen to be meaningful names when the bytes of the chunk type are interpreted as ISO 646 letters. Chunk types are assigned so that a decoder can determine some properties of a chunk even when the type is not recognized. These rules allow safe, flexible extension of the PNG format, by allowing a PNG decoder to decide what to do when it encounters an unknown chunk. (The chunk types standardized in this International Standard are defined in clause 11: Chunk specifications, and the way to add non-standard chunks is defined in clause 14: Editors and extensions.) The naming rules are normally of interest only when the decoder does not recognize the chunk's type.

Four bits of the chunk type, the property bits, namely bit 5 (value 32) of each byte, are used to convey chunk properties. This choice means that a human can read off the assigned properties according to whether the letter corresponding to each byte of the chunk type is uppercase (bit 5 is 0) or lowercase (bit 5 is 1). However, decoders should test the properties of an unknown chunk type by numerically testing the specified bits; testing whether a character is uppercase or lowercase is inefficient, and even incorrect if a locale-specific case definition is used.

The property bits are an inherent part of the chunk type, and hence are fixed for any chunk type. Thus, CHNK and cHNk would be unrelated chunk types, not the same chunk with different properties.

The semantics of the property bits are defined in Table 5.2.

Table 5.2 — Semantics of property bits
Ancillary bit: first byte 0 (uppercase) = critical,
1 (lowercase) = ancillary.
Critical chunks are necessary for successful display of the contents of the datastream, for example the image header chunk (IHDR). A decoder trying to extract the image, upon encountering an unknown chunk type in which the ancillary bit is 0, shall indicate to the user that the image contains information it cannot safely interpret.
Ancillary chunks are not strictly necessary in order to meaningfully display the contents of the datastream, for example the time chunk (tIME). A decoder encountering an unknown chunk type in which the ancillary bit is 1 can safely ignore the chunk and proceed to display the image.
Private bit: second byte 0 (uppercase) = public,
1 (lowercase) = private.
A public chunk is one that is defined in this International Standard or is registered in the list of PNG special-purpose public chunk types maintained by the Registration Authority (see 4.9 Extension and registration). Applications can also define private (unregistered) chunk types for their own purposes. The names of private chunks have a lowercase second letter, while public chunks will always be assigned names with uppercase second letters. Decoders do not need to test the private-chunk property bit, since it has no functional significance; it is simply an administrative convenience to ensure that public and private chunk names will not conflict. See clause 14: Editors and extensions and 12.10.2: Use of private chunks.
Reserved bit: third byte 0 (uppercase) in this version of PNG.
If the reserved bit is 1, the datastream does not conform to this version of PNG.
The significance of the case of the third letter of the chunk name is reserved for possible future extension. In this International Standard, all chunk names shall have uppercase third letters.
Safe-to-copy bit: fourth byte 0 (uppercase) = unsafe to copy,
1 (lowercase) = safe to copy.
This property bit is not of interest to pure decoders, but it is needed by PNG editors. This bit defines the proper handling of unrecognized chunks in a datastream that is being modified. Rules for PNG editors are discussed further in 14.2: Behaviour of PNG editors.

EXAMPLE The hypothetical chunk type "cHNk" has the property bits:

   cHNk  <-- 32 bit chunk type represented in text form
   ||||
   |||+- Safe-to-copy bit is 1 (lower case letter; bit 5 is 1)
   ||+-- Reserved bit is 0     (upper case letter; bit 5 is 0)
   |+--- Private bit is 0      (upper case letter; bit 5 is 0)
   +---- Ancillary bit is 1    (lower case letter; bit 5 is 1)

Therefore, this name represents an ancillary, public, safe-to-copy chunk.

5.5 Cyclic Redundancy Code algorithm

CRC fields are calculated using standardized CRC methods with pre and post conditioning, as defined by ISO 3309 [ISO-3309] and ITU-T V.42 [ITU-T-V42]. The CRC polynomial employed is

x32 + x26 + x23 + x22 + x16 + x12 + x11 + x10 + x8 + x7 + x5 + x4 + x2 + x + 1

In PNG, the 32-bit CRC is initialized to all 1's, and then the data from each byte is processed from the least significant bit (1) to the most significant bit (128). After all the data bytes are processed, the CRC is inverted (its ones complement is taken). This value is transmitted (stored in the datastream) MSB first. For the purpose of separating into bytes and ordering, the least significant bit of the 32-bit CRC is defined to be the coefficient of the x31 term.

Practical calculation of the CRC often employs a precalculated table to accelerate the computation. See Annex D: Sample Cyclic Redundancy Code implementation.

5.6 Chunk ordering

The constraints on the positioning of the individual chunks are listed in Table 5.3 and illustrated diagrammatically in figure 5.2 and figure 5.3. These lattice diagrams represent the constraints on positioning imposed by this International Standard. The lines in the diagrams define partial ordering relationships. Chunks higher up shall appear before chunks lower down. Chunks which are horizontally aligned and appear between two other chunk types (higher and lower than the horizontally aligned chunks) may appear in any order between the two higher and lower chunk types to which they are connected. The superscript associated with the chunk type is defined in Table 5.4. It indicates whether the chunk is mandatory, optional, or may appear more than once. A vertical bar between two chunk types indicates alternatives.

Table 5.3 — Chunk ordering rules
Critical chunks
(shall appear in this order, except PLTE is optional)
Chunk name Multiple allowed Ordering constraints
IHDR No Shall be first
PLTE No Before first IDAT
IDAT Yes Multiple IDAT chunks shall be consecutive
IEND No Shall be last
Ancillary chunks
(need not appear in this order)
Chunk name Multiple allowed Ordering constraints
cHRM No Before PLTE and IDAT
gAMA No Before PLTE and IDAT
iCCP No Before PLTE and IDAT. If the iCCP chunk is present, the sRGB chunk should not be present.
sBIT No Before PLTE and IDAT
sRGB No Before PLTE and IDAT. If the sRGB chunk is present, the iCCP chunk should not be present.
bKGD No After PLTE; before IDAT
hIST No After PLTE; before IDAT
tRNS No After PLTE; before IDAT
pHYs No Before IDAT
sPLT Yes Before IDAT
tIME No None
iTXt Yes None
tEXt Yes None
zTXt Yes None
Table 5.4 — Meaning of symbols used in lattice diagrams
Symbol Meaning
+ One or more
1 Only one
? Zero or one
* Zero or more
| Alternative

Figure 5.2: Lattice diagram: PNG images with PLTE in datastream

Figure 5.2 — Lattice diagram: PNG images with PLTE in datastream

Figure 5.3: Lattice diagram: PNG images without PLTE in datastream

Figure 5.3 — Lattice diagram: PNG images without PLTE in datastream

6 Reference image to PNG image transformation

6.1 Colour types and values

As explained in 4.4: PNG image there are five types of PNG image. Corresponding to each type is a colour type, which is the sum of the following values: 1 (palette used), 2 (truecolour used) and 4 (alpha used). Greyscale and truecolour images may have an explicit alpha channel. The PNG image types and corresponding colour types are listed in Table 6.1.

Table 6.1 — PNG image types and colour types
PNG image type Colour type
Greyscale 0
Truecolour 2
Indexed-colour 3
Greyscale with alpha 4
Truecolour with alpha 6

The allowed bit depths and sample depths for each PNG image type are listed in 11.2.2: IHDR Image header.

Greyscale samples represent luminance if the transfer curve is indicated (by gAMA, sRGB, or iCCP) or device-dependent greyscale if not. RGB samples represent calibrated colour information if the colour space is indicated (by gAMA and cHRM, or sRGB, or iCCP) or uncalibrated device-dependent colour if not.

Sample values are not necessarily proportional to light intensity; the gAMA chunk specifies the relationship between sample values and display output intensity. Viewers are strongly encouraged to compensate properly. See 4.2: Colour spaces, 13.13: Decoder gamma handling and Annex C: Gamma and chromaticity.

6.2 Alpha representation

In a PNG datastream transparency may be represented in one of four ways, depending on the PNG image type (see 4.3.2: Alpha separation and 4.3.5: Alpha compaction).

  1. Truecolour with alpha, greyscale with alpha: an alpha channel is part of the image array.
  2. Truecolour, greyscale: A tRNS chunk contains a single pixel value distinguishing the fully transparent pixels from the fully opaque pixels.
  3. Indexed-colour: A tRNS chunk contains the alpha table that associates an alpha sample with each palette entry.
  4. Truecolour, greyscale, indexed-colour: there is no tRNS chunk present and all pixels are fully opaque.

An alpha channel included in the image array has 8-bit or 16-bit samples, the same size as the other samples. The alpha sample for each pixel is stored immediately following the greyscale or RGB samples of the pixel. An alpha value of zero represents full transparency, and a value of 2sampledepth - 1 represents full opacity. Intermediate values indicate partially transparent pixels that can be composited against a background image to yield the delivered image.

The colour values in a pixel are not premultiplied by the alpha value assigned to the pixel. This rule is sometimes called "unassociated" or "non-premultiplied" alpha. (Another common technique is to store sample values premultiplied by the alpha value; in effect, such an image is already composited against a black background. PNG does not use premultiplied alpha. In consequence an image editor can take a PNG image and easily change its transparency.) See 12.4: Alpha channel creation and 13.16: Alpha channel processing.

7 Encoding the PNG image as a PNG datastream

7.1 Integers and byte order

All integers that require more than one byte shall be in network byte order (as illustrated in figure 7.1): the most significant byte comes first, then the less significant bytes in descending order of significance (MSB LSB for two-byte integers, MSB B2 B1 LSB for four-byte integers). The highest bit (value 128) of a byte is numbered bit 7; the lowest bit (value 1) is numbered bit 0. Values are unsigned unless otherwise noted. Values explicitly noted as signed are represented in two's complement notation.

PNG four-byte unsigned integers are limited to the range 0 to 231-1 to accommodate languages that have difficulty with unsigned four-byte values. Similarly PNG four-byte signed integers are limited to the range -(231-1) to 231-1 to accommodate languages that have difficulty with the value -231.

Figure 7.1: Integer representation in PNG

Figure 7.1 — Integer representation in PNG

7.2 Scanlines

A PNG image (or pass, see clause 8: Interlacing and pass extraction) is a rectangular pixel array, with pixels appearing left-to-right within each scanline, and scanlines appearing top-to-bottom. The size of each pixel is determined by the number of bits per pixel.

Pixels within a scanline are always packed into a sequence of bytes with no wasted bits between pixels. Scanlines always begin on byte boundaries. Permitted bit depths and colour types are restricted so that in all cases the packing is simple and efficient.

In PNG images of colour type 0 (greyscale) each pixel is a single sample, which may have precision less than a byte (1, 2, or 4 bits). These samples are packed into bytes with the leftmost sample in the high-order bits of a byte followed by the other samples for the scanline.

In PNG images of colour type 3 (indexed-colour) each pixel is a single palette index. These indices are packed into bytes in the same way as the samples for colour type 0.

When there are multiple pixels per byte, some low-order bits of the last byte of a scanline may go unused. The contents of these unused bits are not specified.

PNG images that are not indexed-colour images may have sample values with a bit depth of 16. Such sample values are in network byte order (MSB first, LSB second). PNG permits multi-sample pixels only with 8 and 16-bit samples, so multiple samples of a single pixel are never packed into one byte.

7.3 Filtering

PNG allows the scanline data to be filtered before it is compressed. Filtering can improve the compressibility of the data. The filter step itself results in a sequence of bytes of the same size as the incoming sequence, but in a different representation, preceded by a filter type byte. Filtering does not reduce the size of the actual scanline data. All PNG filters are strictly lossless.

Different filter types can be used for different scanlines, and the filter algorithm is specified for each scanline by a filter type byte. The filter type byte is not considered part of the image data, but it is included in the datastream sent to the compression step. An intelligent encoder can switch filters from one scanline to the next. The method for choosing which filter to employ is left to the encoder.

See clause 9: Filtering.

8 Interlacing and pass extraction

8.1 Introduction

Pass extraction (see figure 4.8) splits a PNG image into a sequence of reduced images (the interlaced PNG image) where the first image defines a coarse view and subsequent images enhance this coarse view until the last image completes the PNG image. This allows progressive display of the interlaced PNG image by the decoder and allows images to "fade in" when they are being displayed on-the-fly. On average, interlacing slightly expands the datastream size, but it can give the user a meaningful display much more rapidly.

8.2 Interlace methods

Two interlace methods are defined in this International Standard, methods 0 and 1. Other values of interlace method are reserved for future standardization (see 4.9: Extension and registration).

With interlace method 0, the null method, pixels are extracted sequentially from left to right, and scanlines sequentially from top to bottom. The interlaced PNG image is a single reduced image.

Interlace method 1, known as Adam7, defines seven distinct passes over the image. Each pass transmits a subset of the pixels in the reference image. The pass in which each pixel is transmitted (numbered from 1 to 7) is defined by replicating the following 8-by-8 pattern over the entire image, starting at the upper left corner:

   1 6 4 6 2 6 4 6
   7 7 7 7 7 7 7 7
   5 6 5 6 5 6 5 6
   7 7 7 7 7 7 7 7
   3 6 4 6 3 6 4 6
   7 7 7 7 7 7 7 7
   5 6 5 6 5 6 5 6
   7 7 7 7 7 7 7 7

Figure 4.8 shows the seven passes of interlace method 1. Within each pass, the selected pixels are transmitted left to right within a scanline, and selected scanlines sequentially from top to bottom. For example, pass 2 contains pixels 4, 12, 20, etc. of scanlines 0, 8, 16, etc. (where scanline 0, pixel 0 is the upper left corner). The last pass contains all of scanlines 1, 3, 5, etc. The transmission order is defined so that all the scanlines transmitted in a pass will have the same number of pixels; this is necessary for proper application of some of the filters. The interlaced PNG image consists of a sequence of seven reduced images. For example, if the PNG image is 16 by 16 pixels, then the third pass will be a reduced image of two scanlines, each containing four pixels (see figure 4.8).

Scanlines that do not completely fill an integral number of bytes are padded as defined in 7.2: Scanlines.

NOTE If the reference image contains fewer than five columns or fewer than five rows, some passes will be empty.

9 Filtering

9.1 Filter methods and filter types

Filtering transforms the PNG image with the goal of improving compression. PNG allows for a number of filter methods. All the reduced images in an interlaced image shall use a single filter method. Only filter method 0 is defined by this International Standard. Other filter methods are reserved for future standardization (see 4.9 Extension and registration). Filter method 0 provides a set of five filter types, and individual scanlines in each reduced image may use different filter types.

PNG imposes no additional restriction on which filter types can be applied to an interlaced PNG image. However, the filter types are not equally effective on all types of data. See 12.8: Filter selection.

Filtering transforms the byte sequence in a scanline to an equal length sequence of bytes preceded by the filter type. Filter type bytes are associated only with non-empty scanlines. No filter type bytes are present in an empty pass. See 13.8: Interlacing and progressive display.

9.2 Filter types for filter method 0

Filters are applied to bytes, not to pixels, regardless of the bit depth or colour type of the image. The filters operate on the byte sequence formed by a scanline that has been represented as described in 7.2: Scanlines. If the image includes an alpha channel, the alpha data is filtered in the same way as the image data.

Filters may use the original values of the following bytes to generate the new byte value:

x the byte being filtered;
a the byte corresponding to x in the pixel immediately before the pixel containing x (or the byte immediately before x, when the bit depth is less than 8);
b the byte corresponding to x in the previous scanline;
c the byte corresponding to b in the pixel immediately before the pixel containing b (or the byte immediately before b, when the bit depth is less than 8).

Figure 9.1 shows the relative positions of the bytes x, a, b, and c.

PNG filter method 0 defines five basic filter types as listed in Table 9.1. Orig(y) denotes the orginal (unfiltered) value of byte y. Filt(y) denotes the value after a filter has been applied. Recon(y) denotes the value after the corresponding reconstruction function has been applied. The filter function for the Paeth type PaethPredictor is defined below.

Filter method 0 specifies exactly this set of five filter types and this shall not be extended. This ensures that decoders need not decompress the data to determine whether it contains unsupported filter types: it is sufficient to check the filter method in IHDR.

Table 9.1 — Filter types
Type Name Filter Function Reconstruction Function
0 None Filt(x) = Orig(x) Recon(x) = Filt(x)
1 Sub Filt(x) = Orig(x) - Orig(a) Recon(x) = Filt(x) + Recon(a)
2 Up Filt(x) = Orig(x) - Orig(b) Recon(x) = Filt(x) + Recon(b)
3 Average Filt(x) = Orig(x) - floor((Orig(a) + Orig(b)) / 2) Recon(x) = Filt(x) + floor((Recon(a) + Recon(b)) / 2)
4 Paeth Filt(x) = Orig(x) - PaethPredictor(Orig(a), Orig(b), Orig(c)) Recon(x) = Filt(x) + PaethPredictor(Recon(a), Recon(b), Recon(c))

For all filters, the bytes "to the left of" the first pixel in a scanline shall be treated as being zero. For filters that refer to the prior scanline, the entire prior scanline and bytes "to the left of" the first pixel in the prior scanline shall be treated as being zeroes for the first scanline of a reduced image.

To reverse the effect of a filter requires the decoded values of the prior pixel on the same scanline, the pixel immediately above the current pixel on the prior scanline, and the pixel just to the left of the pixel above.

Unsigned arithmetic modulo 256 is used, so that both the inputs and outputs fit into bytes. Filters are applied to each byte regardless of bit depth. The sequence of Filt values is transmitted as the filtered scanline.

9.3 Filter type 3: Average

The sum Orig(a) + Orig(b) shall be performed without overflow (using at least nine-bit arithmetic). floor() indicates that the result of the division is rounded to the next lower integer if fractional; in other words, it is an integer division or right shift operation.

9.4 Filter type 4: Paeth

The Paeth filter function computes a simple linear function of the three neighbouring pixels (left, above, upper left), then chooses as predictor the neighbouring pixel closest to the computed value. The algorithm used in this International Standard is an adaptation of the technique due to Alan W. Paeth [PAETH].

The PaethPredictor function is defined in the code below. The logic of the function and the locations of the bytes a, b, c, and x are shown in figure 9.1. Pr is the predictor for byte x.

    p = a + b - c
    pa = abs(p - a)
    pb = abs(p - b)
    pc = abs(p - c)
    if pa <= pb and pa <= pc then Pr = a
    else if pb <= pc then Pr = b
    else Pr = c
    return Pr

Figure 9.1: The PaethPredictor
function

Figure 9.1: The PaethPredictor function

The calculations within the PaethPredictor function shall be performed exactly, without overflow.

The order in which the comparisons are performed is critical and shall not be altered. The function tries to establish in which of the three directions (vertical, horizontal, or diagonal) the gradient of the image is smallest.

Exactly the same PaethPredictor function is used by both encoder and decoder.

10 Compression

10.1 Compression method 0

Only PNG compression method 0 is defined by this International Standard. Other values of compression method are reserved for future standardization (see 4.9: Extension and registration). PNG compression method 0 is deflate/inflate compression with a sliding window (which is an upper bound on the distances appearing in the deflate stream) of at most 32768 bytes. Deflate compression is an LZ77 derivative [ZL].

Deflate-compressed datastreams within PNG are stored in the "zlib" format, which has the structure:

zlib compression method/flags code 1 byte
Additional flags/check bits 1 byte
Compressed data blocks n bytes
Check value 4 bytes

Further details on this format are given in the zlib specification [RFC-1950].

For PNG compression method 0, the zlib compression method/flags code shall specify method code 8 (deflate compression) and an LZ77 window size of not more than 32768 bytes. The zlib compression method number is not the same as the PNG compression method number in the IHDR chunk (see 11.2.2 IHDR Image header). The additional flags shall not specify a preset dictionary.

If the data to be compressed contain 16384 bytes or fewer, the PNG encoder may set the window size by rounding up to a power of 2 (256 minimum). This decreases the memory required for both encoding and decoding, without adversely affecting the compression ratio.

The compressed data within the zlib datastream are stored as a series of blocks, each of which can represent raw (uncompressed) data, LZ77-compressed data encoded with fixed Huffman codes, or LZ77-compressed data encoded with custom Huffman codes. A marker bit in the final block identifies it as the last block, allowing the decoder to recognize the end of the compressed datastream. Further details on the compression algorithm and the encoding are given in the deflate specification [RFC-1951].

The check value stored at the end of the zlib datastream is calculated on the uncompressed data represented by the datastream. The algorithm used to calculate this is not the same as the CRC calculation used for PNG chunk CRC field values. The zlib check value is useful mainly as a cross-check that the deflate and inflate algorithms are implemented correctly. Verifying the individual PNG chunk CRCs provides confidence that the PNG datastream has been transmitted undamaged.

10.2 Compression of the sequence of filtered scanlines

The sequence of filtered scanlines is compressed and the resulting data stream is split into IDAT chunks. The concatenation of the contents of all the IDAT chunks makes up a zlib datastream. This datastream decompresses to filtered image data.

It is important to emphasize that the boundaries between IDAT chunks are arbitrary and can fall anywhere in the zlib datastream. There is not necessarily any correlation between IDAT chunk boundaries and deflate block boundaries or any other feature of the zlib data. For example, it is entirely possible for the terminating zlib check value to be split across IDAT chunks.

Similarly, there is no required correlation between the structure of the image data (i.e., scanline boundaries) and deflate block boundaries or IDAT chunk boundaries. The complete filtered PNG image is represented by a single zlib datastream that is stored in a number of IDAT chunks.

10.3 Other uses of compression

PNG also uses compression method 0 in iTXt, iCCP, and zTXt chunks. Unlike the image data, such datastreams are not split across chunks; each such chunk contains an independent zlib datastream (see 10.1: Compression method 0).

11 Chunk specifications

11.1 Introduction

The PNG datastream consists of a PNG signature (see 5.2: PNG signature) followed by a sequence of chunks. Each chunk has a chunk type which specifies its function. This clause defines the PNG chunk types standardized in this International Standard. The PNG datastream structure is defined in clause 5: Datastream structure. This also defines the order in which chunks may appear. For details specific to encoders see 12.11: Chunking. For details specific to decoders see 13.5: Chunking.

11.2 Critical chunks

11.2.1 General

Critical chunks are those chunks that are absolutely required in order to successfully decode a PNG image from a PNG datastream. Extension chunks may be defined as critical chunks (see clause 14: Editors and extensions), though this practice is strongly discouraged.

A valid PNG datastream shall begin with a PNG signature, immediately followed by an IHDR chunk, then one or more IDAT chunks, and shall end with an IEND chunk. Only one IHDR chunk and one IEND chunk are allowed in a PNG datastream.

11.2.2 IHDR Image header

The four-byte chunk type field contains the decimal values

73 72 68 82

The IHDR chunk shall be the first chunk in the PNG datastream. It contains:

Width 4 bytes
Height 4 bytes
Bit depth 1 byte
Colour type 1 byte
Compression method 1 byte
Filter method 1 byte
Interlace method 1 byte

Width and height give the image dimensions in pixels. They are PNG four-byte unsigned integers. Zero is an invalid value.

Bit depth is a single-byte integer giving the number of bits per sample or per palette index (not per pixel). Valid values are 1, 2, 4, 8, and 16, although not all values are allowed for all colour types. See 6.1: Colour types and values.

Colour type is a single-byte integer that defines the PNG image type. Valid values are 0, 2, 3, 4, and 6.

Bit depth restrictions for each colour type are imposed to simplify implementations and to prohibit combin