Class: Pura::Gif::Encoder

Inherits:
Object
  • Object
show all
Defined in:
lib/pura/gif/encoder.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(image, max_colors: 256) ⇒ Encoder

Returns a new instance of Encoder.



12
13
14
15
16
# File 'lib/pura/gif/encoder.rb', line 12

def initialize(image, max_colors: 256)
  @image = image
  @max_colors = [max_colors, 256].min
  @max_colors = 2 if @max_colors < 2
end

Class Method Details

.encode(image, output_path, max_colors: 256) ⇒ Object



6
7
8
9
10
# File 'lib/pura/gif/encoder.rb', line 6

def self.encode(image, output_path, max_colors: 256)
  data = new(image, max_colors: max_colors).encode
  File.binwrite(output_path, data)
  data.bytesize
end

Instance Method Details

#encodeObject



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/pura/gif/encoder.rb', line 18

def encode
  # Quantize RGB pixels to a palette of at most @max_colors
  palette, indices = quantize(@image.pixels, @image.width, @image.height, @max_colors)

  # Pad palette to next power of 2 (minimum 4 entries for min_code_size >= 2)
  palette_bits = 1
  palette_bits += 1 while (1 << palette_bits) < palette.length
  palette_bits = 2 if palette_bits < 2
  palette_size = 1 << palette_bits

  palette << [0, 0, 0] while palette.length < palette_size

  min_code_size = palette_bits

  # LZW compress the indices
  compressed = lzw_compress(indices, min_code_size)

  # Build the GIF binary
  out = String.new(encoding: Encoding::BINARY)

  # Header
  out << "GIF89a"

  # Logical Screen Descriptor
  out << [@image.width, @image.height].pack("v2")
  packed = 0x80 | ((palette_bits - 1) << 4) | (palette_bits - 1)
  out << packed.chr << "\x00".b << "\x00".b

  # Global Color Table
  palette.each do |r, g, b|
    out << r.chr << g.chr << b.chr
  end

  # Image Descriptor
  out << "\x2C".b
  out << [0, 0, @image.width, @image.height].pack("v4")
  out << "\x00".b # packed: no local color table, not interlaced

  # Image Data
  out << min_code_size.chr

  # Write compressed data as sub-blocks (max 255 bytes each)
  pos = 0
  while pos < compressed.bytesize
    chunk_size = [compressed.bytesize - pos, 255].min
    out << chunk_size.chr
    out << compressed.byteslice(pos, chunk_size)
    pos += chunk_size
  end
  out << "\x00".b # block terminator

  # Trailer
  out << "\x3B".b

  out
end