Module: ChunkyPNG::Chunk

Defined in:
lib/chunky_png/chunk.rb

Overview

A PNG datastream consists of multiple chunks. This module, and the classes contained within, help with handling these chunks. It supports both reading and writing chunks.

All chunk types are instances of the Base class. For some chunk types a specialized class is available, e.g. the IHDR chunk is represented by the Header class. These specialized classes help accessing the content of the chunk. All other chunks are represented by the Generic class.

See Also:

Defined Under Namespace

Classes: Base, CompressedText, End, Generic, Header, ImageData, InternationalText, Palette, Text, Transparency

Constant Summary

CHUNK_TYPES =

Maps chunk types to classes, based on the four byte chunk type indicator at the beginning of a chunk.

If a chunk type is not specified in this hash, the Generic chunk type will be used.

See Also:

{
  'IHDR' => Header, 'IEND' => End, 'IDAT' => ImageData, 'PLTE' => Palette, 'tRNS' => Transparency,
  'tEXt' => Text, 'zTXt' => CompressedText, 'iTXt' => InternationalText
}

Class Method Summary (collapse)

Class Method Details

+ (ChunkyPNG::Chung::Base) read(io)

Reads a chunk from an IO stream.

Parameters:

  • io (IO, #read)

    The IO stream to read from.

Returns:

  • (ChunkyPNG::Chung::Base)

    The loaded chunk instance.



20
21
22
23
24
25
26
27
28
29
# File 'lib/chunky_png/chunk.rb', line 20

def self.read(io)

  length, type = io.read(8).unpack('Na4')
  content      = io.read(length)
  crc          = io.read(4).unpack('N').first

  verify_crc!(type, content, crc)

  CHUNK_TYPES.fetch(type, Generic).read(type, content)
end

+ (Object) verify_crc!(type, content, found_crc)

Verifies the CRC of a chunk.

Parameters:

  • type (String)

    The chunk's type.

  • content (String)

    The chunk's content.

  • content (Integer)

    The chunk's content.

Raises:

  • (RuntimeError)

    An exception is raised if the found CRC value is not equal to the expected CRC value.



37
38
39
40
# File 'lib/chunky_png/chunk.rb', line 37

def self.verify_crc!(type, content, found_crc)
  expected_crc = Zlib.crc32(content, Zlib.crc32(type))
  raise ChunkyPNG::CRCMismatch, "Chuck CRC mismatch!" if found_crc != expected_crc
end