Pseudocode
PNG decoding
Bit manipulation
Programming
Image processing

Pseudocode How to decode a PNG file from bits and bytes?

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

PNG files, or Portable Network Graphics, are widely used due to their lossless compression and support for transparency. Understanding how to decode a PNG file from its bits and bytes involves unpicking a series of structured data chunks. In this article, we will explore the PNG format and provide a detailed pseudocode explanation for decoding it.

Understanding PNG File Structure

A PNG file is composed of an 8-byte signature followed by a series of chunks. Each chunk has a specific function and contributes to rendering the image correctly.

PNG Signature

Every PNG file begins with an 8-byte signature:

 
Hex: 89 50 4E 47 0D 0A 1A 0A
Decimal: 137 80 78 71 13 10 26 10

This signature helps identify the file as a PNG and ensures data integrity.

Data Chunks

PNG files are organized in chunks, where each chunk consists of:

  • Length (4 bytes): The length of the chunk's data field.
  • Chunk Type (4 bytes): A 4-character ASCII identifier with specific properties.
  • Chunk Data: The chunk's actual data (length-byte long).
  • CRC (4 bytes): A CRC-32 error-detecting code for verifying correctness.

Critical Chunks

  1. IHDR (Image Header):
    • Contains essential information for displaying the image, such as width, height, color type, etc.
  2. IDAT (Image Data):
    • Stores the compressed image data.
  3. IEND (Image End):
    • Marks the end of the PNG file.

Ancillary Chunks

Ancillary chunks contain metadata such as text comments, gamma correction information, etc. They're not crucial for rendering the image but provide additional context.

Decoding PNG File: Pseudocode

To decode a PNG file into an image, we follow a structured approach. Let's break down the steps in pseudocode:

Step 1: Read and Validate the PNG Signature

plaintext
1function validatePngSignature(file):
2    signature = readNextBytes(file, 8)
3    expectedSignature = [137, 80, 78, 71, 13, 10, 26, 10]
4    if signature != expectedSignature:
5        raise Error("Not a valid PNG file")

Step 2: Process Chunks

plaintext
1function processChunks(file):
2    while not endOfFile(file):
3        length = readNextBytes(file, 4) // Read the length of the following chunk
4        chunkType = readNextBytes(file, 4) // Read the chunk type identifier
5        data = readNextBytes(file, length) // Read the chunk data
6        crc = readNextBytes(file, 4)        // Read the CRC
7
8        if not validateCRC(chunkType, data, crc):
9            raise Error("CRC mismatch")
10
11        switch chunkType:
12            case "IHDR":
13                processIHDR(data)
14            case "IDAT":
15                processIDAT(data)
16            case "IEND":
17                processIEND(data)
18                break // end of the file
19            default:
20                processAncillaryChunk(chunkType, data)

Step 3: Extract Image Data from IDAT

plaintext
1function processIDAT(data):
2    decompressedData = decompress(data)
3    scanlines = parseScanlines(decompressedData)
4    reconstructImage(scanlines)

Step 4: Reconstruct Image

plaintext
1function reconstructImage(scanlines):
2    for each scanline in scanlines:
3        filterType = scanline[0] // First byte is the filter type
4        revertFilter(scanline[1:], filterType)
5
6    // convert reconstructed data into image pixels

Key Points Summary

Below is a summary of key points involved in decoding a PNG file:

Key AreaDetails
PNG SignatureIdentifies PNG with 89 50 4E 47 0D 0A 1A 0A
Chunks StructureContains Length, Chunk Type, Chunk Data, CRC
Critical ChunksIHDR (Header), IDAT (Data), IEND (End of file)
Ancillary ChunksProvide metadata like text, gamma info
Decoding StepsValidate signature > Process chunks > Extract IDAT > Reconstruct image
Color TypesUpdated by IHDR; affects how image data is interpreted

Additional Details: Color Types and Filters

The IHDR chunk specifies the color type, which affects how pixel data is interpreted. PNG supports several color types, such as Grayscale, Truecolor, and Indexed color. Filters applied to scanlines help improve compression; these include None, Sub, Up, Average, and Paeth.

Decoding a PNG involves understanding these intricacies and applying correct methods to reconstruct the image from processed data. Observing filesize limits and adhering to PNG specifications are vital to successful decoding and image rendering.


Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

All Rights Reserved.