Class: AnimatedGifDetector

Inherits:
Object
  • Object
show all
Defined in:
lib/animated_gif_detector.rb,
lib/animated_gif_detector/version.rb

Defined Under Namespace

Classes: EOFWithoutFrameException, UnrecognizedFileFormatException

Constant Summary collapse

BLOCK_TERMINATOR =
0x00.chr
GRAPHIC_CONTROL_EXTENSION_MAGIC =
0x21.chr + 0xF9.chr
BLOCK_SIZE =
(BLOCK_TERMINATOR + GRAPHIC_CONTROL_EXTENSION_MAGIC).size
VERSION =
"0.1.1"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(io, options = {}) ⇒ AnimatedGifDetector

Returns a new instance of AnimatedGifDetector.



15
16
17
18
19
# File 'lib/animated_gif_detector.rb', line 15

def initialize(io, options = {})
  @options = { buffer_size: 1024, terminate_after: true }.merge(options)
  @stream = io
  @frames = 0
end

Instance Attribute Details

#framesObject (readonly)



9
10
11
# File 'lib/animated_gif_detector.rb', line 9

def frames
  @frames
end

Instance Method Details

#animated?Boolean

Returns:

  • (Boolean)


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
# File 'lib/animated_gif_detector.rb', line 21

def animated?
  return @animated if defined? @animated
  @animated = begin
    raise UnrecognizedFileFormatException unless @stream.read(3) == 'GIF'

    lookback = ''
    animated = false
    while data = @stream.read(@options[:buffer_size])
      @frames += count_substring_matches(lookback + data, BLOCK_TERMINATOR + GRAPHIC_CONTROL_EXTENSION_MAGIC)
      animated = @frames > 1

      if @options[:terminate_after] && animated
        @animated = true
        return true
      end

      lookback = last_characters(data, BLOCK_SIZE - 1)
    end

    raise EOFWithoutFrameException if @frames == 0
    animated
  end
ensure
  @stream.rewind
end