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

Where

PNG Header:

OffsetHex ValueASCII
089
150P
24EN
347G
40D
50A
61A
70A

Example:
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).

Example:
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
http://www.w3.org/TR/PNG-Chunks.html
http://www.libpng.org/pub/png/book/chapter11.html

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 http://www.labbookpages.co.uk/software/imgProc/libPNG.html 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 http://stackoverflow.com/questions/1821806/how-to-encode-png-to-buffer-using-libpng

3 comments:

https://www.hotsexyescort.com/richmond-london.html said...

I really like your blog post very much. You have really shared a informative and interesting blog post with people..
Thank you so much for your very kind words and I am so glad you find comfort here. Sending love !

Malcolm Burrows said...

PNG files are more useful as it uses the lossless compression so the decompression will give pretty much the same image back. feel free to visit https://applesupportnumber.net/blog/fix-iphone-error-4013/

jhon01djon said...

I really like your blog post very much. If anyone who wants help for national debt relief then they can visit debt relief order the UK from our debt relief organization.