Module: Gifenc::Util

Defined in:
lib/util.rb

Overview

Encapsulates generic functionality that is useful when handling GIF files.

Class Method Summary collapse

Class Method Details

.blockify(data) ⇒ String

Divide data block into a series of sub-blocks of size at most 256 bytes each, consisting on a 1-byte prefix indicating the block length, and <255 bytes of actual data, with a null terminator at the end. This is how raw data (e.g. compressed pixel data or extension data) is stored in GIFs.

Parameters:

  • data (String)

    Data to lay into sub-blocks.

Returns:

  • (String)

    The resulting data in block fashion.



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/util.rb', line 12

def self.blockify(data)
  return BLOCK_TERMINATOR if data.size == 0
  ff = "\xFF".b.freeze
  off = 0
  out = "".b
  len = data.length
  for _ in (0 ... len / 255)
    out << ff << data[off ... off + 255]
    off += 255
  end
  out << (len - off).chr << data[off..-1] if off < len
  out << BLOCK_TERMINATOR
  out
rescue
  BLOCK_TERMINATOR
end

.deblockify(data) ⇒ String

Recover original data from inside the 256-byte blocks used by GIF.

Parameters:

  • data (String)

    Data in blocks to read.

Returns:

  • (String)

    Original raw data.



32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/util.rb', line 32

def self.deblockify(data)
  out = ""
  size = data[0].ord
  off = 0
  while size != 0
    out << data[off + 1 .. off + size]
    off += size + 1
    size = data[off].ord
  end
  out
rescue
  ''.b
end

.lzw_encode(data, min_bits = 8) ⇒ String

Encode data using LZW compliant with GIF specification. to encode all the symbols present in the data, and at most 12.

Parameters:

  • data (String)

    Binary string containing the arbitrary data to encode.

  • min_bits (Integer) (defaults to: 8)

    Minimum bits for each LZW code. Should be enough

Returns:

  • (String)

    Binary string containing the encoded data.



51
52
53
54
# File 'lib/util.rb', line 51

def self.lzw_encode(data, min_bits = 8)
  lzw = LZWrb.new(preset: LZWrb::PRESET_GIF, min_bits: min_bits, verbosity: :minimal)
  min_bits.chr + Util.blockify(lzw.encode(data))
end