Saturday, November 1, 2014

Basics of PNG File Format with libPNG example

PNG (Portable Network Graphic) is well known image format used widely over internet. PNG is lossless compressed image file format due to which it is the most favorable file format of images which are likely to be transferred over network. A PNG file consists of PNG Header + Multiple PNG Chunks. A simple PNG file consist of following structure

PNG Header + IHDR Chunk + IDAT Chunk + IEND Chunk


PNG Header:

OffsetHex ValueASCII

89 50 4E 47 0D 0A 1A 0A

PNG Chunk : Structure of chunk is shown below. A single PNG file can contains multiple chunks of different type. Type is identified using Chunk Type field. Each type of field has its own interpretation.

  • Data Length (4 byte)
  • Chunk Type (4 byte ASCII name)
  • Data Bytes
  • CRC (4 byte)

IHDR Chunk: Length of IHDR is fixed 13 bytes and its data field consists of
Image Width (4 byte)
Image Height (4 byte)
Color Depth (1 byte)
Color Type  (1 byte)
Compression method (1 byte),
Filter method (1 Byte)
Interlace method (1 byte).

00 00 00 0D 49 48 44 52 00 00 01 F4 00 00 00 64 08 06 00 00 00 70 C7 C2 7D

IDAT: This chunk contains the compressed image pixel data. A PNG file can have multiple IDAT chunks which will allows the renderer application (like web browser) to display part of image as when the chunk will be available and loading remaining image at the same time.

IEND: This chunks indicates the that are no more chunks. It contains 0 bytes data . It always comes at the END of PNG file. Hex output of
00 00 00 00 49 45 4e 44 ae 42 60 82

Summary related to other common types of chunk is available at

libPNG is open source library used to decode and encode PNG files. A very good example on how to create a PNG image is available at but this example creates PNG file on disk what if we want to write PNG into buffer?
To achieve that we can use png_set_write_fn as mention on this post

No comments: