Pseudocode: How to decode a PNG file from bits and bytes? : <p>I've been trying to figure this out by reverse engineering a .png file I created in GIMP. It's 4x4 pixels. My goal is to decode the raw pixels out of the file with the intent of reversing this to encode.  </p>

<p>Here is a full hex dump of the file:  </p>

<pre><code>89504E47 0D0A1A0A 0000000D 49484452 00000004 00000004  
08020000 00269309 29000000 3F494441 54081D01 3400CBFF  
01CC96B1 134FE120 C0CECDF1 5101FFA5 60000000 000000E0  
403201DF E59286DF 6D000000 00000004 EDB11F00 2E007A21  
93EDB11F 3063136F 4733525A 00000000 49454E44 AE426082  
</code></pre>

<p>According to the <a href="http://www.libpng.org/pub/png/spec/1.2/PNG-Structure.html" rel="noreferrer">spec</a>, we start with the PNG signature which is the first 8 bytes.  </p>

<blockquote>
  <p>89504E47 0D0A1A0A  </p>
</blockquote>

<p>We then have repeating "chunk" structures, this file has 3 "chunks", the header (IHDR), the image data (IDAT) and then the end "chunk" (IEND).  </p>

<p>Each chunk is arranged into: the first 4 bytes for the length of the chunk data, the next 4 bytes for the type of data, then n-bytes for the actual data and then 4 bytes for the cyclic redundancy check (CRC) of the type of data and actual data sections. </p>

<p>Following this through...  </p>

<blockquote>
  <p>0000000D  </p>
</blockquote>

<p>Is the chunk's data length (13 bytes).  </p>

<blockquote>
  <p>49484452  </p>
</blockquote>

<p>Is the chunk's type (IHDR).  </p>

<blockquote>
  <p>00000004 00000004 08020000 00  </p>
</blockquote>

<p>Is the chunk's data (4 bytes width, height; 1 byte bit depth, colour type, compression method, filter method, interlace method).  </p>

<blockquote>
  <p>269309 29  </p>
</blockquote>

<p>Is the CRC of the data and type (managed to get the code to work this out from <a href="http://www.libpng.org/pub/png/spec/1.2/PNG-CRCAppendix.html" rel="noreferrer">here</a>.  </p>

<blockquote>
  <p>000000 3F  </p>
</blockquote>

<p>Is the next chunk's data length (63 bytes).</p>

<blockquote>
  <p>494441 54  </p>
</blockquote>

<p>Is the chunk's type (IDAT).  </p>

<blockquote>
  <p>081D01 3400CBFF 01CC96B1 134FE120 C0CECDF1 5101FFA5 60000000 000000E0 403201DF E59286DF 6D000000 00000004 EDB11F00 2E007A21 93EDB11F 3063136F  </p>
</blockquote>

<p>Is the chunk's actual data (the image data compressed and filtered).  </p>

<p>So my actual question is how do I decode this last section into raw pixels?  </p>

<p>According to the <a href="http://www.libpng.org/pub/png/spec/1.2/PNG-Chunks.html#C.IDAT" rel="noreferrer">spec</a>, I must first decompress the data (INFLATE?) and then unfilter it (??) to be left with scanlines of pixels (my goal).  </p>

<p><strong>If this could be explained in pseudocode that would be amazing! Otherwise I'm familiar with Swift and less so with C...</strong></p>
