Module | ChunkyPNG::Chunk |
In: |
lib/chunky_png/chunk.rb
|
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 {ChunkyPNG::Chunk::Base} class. For some chunk types a specialized class is available, e.g. the IHDR chunk is represented by the {ChunkyPNG::Chunk::Header} class. These specialized classes help accessing the content of the chunk. All other chunks are represented by the {ChunkyPNG::Chunk::Generic} class.
CHUNK_TYPES | = | { 'IHDR' => Header, 'IEND' => End, 'IDAT' => ImageData, 'PLTE' => Palette, 'tRNS' => Transparency, 'tEXt' => Text, 'zTXt' => CompressedText, 'iTXt' => InternationalText |
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. |
Reads a chunk from an IO stream.
@param [IO, read] io The IO stream to read from. @return [ChunkyPNG::Chung::Base] The loaded chunk instance.
# File lib/chunky_png/chunk.rb, line 20 20: def self.read(io) 21: 22: length, type = io.read(8).unpack('Na4') 23: content = io.read(length) 24: crc = io.read(4).unpack('N').first 25: 26: verify_crc!(type, content, crc) 27: 28: CHUNK_TYPES.fetch(type, Generic).read(type, content) 29: end
Verifies the CRC of a chunk. @param [String] type The chunk‘s type. @param [String] content The chunk‘s content. @param [Integer] content The chunk‘s content. @raise [RuntimeError] An exception is raised if the found CRC value
is not equal to the expected CRC value.
# File lib/chunky_png/chunk.rb, line 37 37: def self.verify_crc!(type, content, found_crc) 38: expected_crc = Zlib.crc32(content, Zlib.crc32(type)) 39: raise ChunkyPNG::CRCMismatch, "Chuck CRC mismatch!" if found_crc != expected_crc 40: end