How the heck is PNG data encoded?

592 views

I do not understand the Portable Network Graphics format. So the first byte in the raw data is `0x89`, then ASCII for `PNG` for when someone opens a PNG image in a text editor, then `0x0D 0x0A` followed by `0x1A` and `0x0A`, so what do these mean? Also what are the 4 byte ‘chunks?’ How can this be translate this to raw pixel data, like `[R, G, B, A, R, G, B, A, …]`? How does the format work? What do I need to know to effectively be able to edit PNG via a hex editor, or better, writing raw RGB data and ***somehow*** encoding that to PNG? Where is the ‘red pixel’ bytes in the Wikipedia example? `89 50 4E 47 0D 0A 1A 0A 00 00 00 0D 49 48 44 52 00 00 00 01 00 00 00 01 08 02 00 00 00 90 77 53 DE 00 00 00 0C 49 44 41 54 08 D7 63 F8 CF C0 00 00 03 01 01 00 18 DD 8D B0 00 00 00 00 49 45 4E 44 AE 42 60 82`

In: Technology

2 Answers

Anonymous 0 Comments

The chunks are not 4 bytes. The chunks are arbitrary lengths, but the “start of chunk” has the length of the chunk. So after the 0x0A, you start reading the chunks. The first 4 bytes are the length of the data in the chunk. The next 4 bytes are a chunk “type” identifier. Next is the actual chunk data of X bytes specified at the start of the chunk. After you’ve read X bytes, you have 4 bytes as a CRC checksum to make sure the data hasn’t been corrupted.

So in your example, after the header is 4 bytes of “00 00 00 0D”, so that means your chunk is 13 bytes long. The next 4 bytes are “49 48 44 52”, which means “IHDR” header. That gives the PNG image info (height, width, depth) in that 13 bytes. There’s additional headers in there as well

Anonymous 0 Comments

PNG is a compressed format. It doesn’t store the raw RGBA values, it packs the bits into less space using a special algorithm. It’s not rocket science, but if you wanted to do it for anything larger than a 4×4 it wouldn’t be realistic to do it by hand. It’s meant to be run as an algorithm.

There are several tutorials that explain it at a high level, like this one:

[https://medium.com/@duhroach/how-png-works-f1174e3cc7b7](https://medium.com/@duhroach/how-png-works-f1174e3cc7b7)

Or you can read the full specification in all its gory detail:

[https://www.w3.org/TR/2003/REC-PNG-20031110/](https://www.w3.org/TR/2003/REC-PNG-20031110/)

Can you say anything more about what you want to do? It’s possible another file format like TIFF or XPM might suit your needs better; they allow uncompressed data so you could make one with a hex editor.