Skip to content

Instantly share code, notes, and snippets.

@namusyaka
Last active August 29, 2015 14:13
Show Gist options
  • Save namusyaka/ff945a5fe47b8e91faad to your computer and use it in GitHub Desktop.
Save namusyaka/ff945a5fe47b8e91faad to your computer and use it in GitHub Desktop.

Revisions

  1. namusyaka revised this gist Jan 10, 2015. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion gistfile1.rb
    Original file line number Diff line number Diff line change
    @@ -60,7 +60,7 @@ def each_duration(&block)
    if @duration.respond_to?(:call)
    @duration.call @movie
    else
    @duration.instance_of?(Range) ? @duration.each : @duration.times
    @duration.instance_of?(Range) ? @duration : @duration.times
    end.each(&block)
    end
    end
  2. namusyaka created this gist Jan 10, 2015.
    66 changes: 66 additions & 0 deletions gistfile1.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,66 @@
    require 'fileutils'
    require 'RMagick'
    require 'streamio-ffmpeg'

    class Turmeric
    DEFAULT_OPTIONS = {
    tmp_dir: "./tmp/",
    resolution: "200x100",
    duration: ->(movie){ movie.duration.to_i.times }
    }.freeze

    attr_accessor :tmp_dir, :resolution, :duration
    attr_reader :frames

    def initialize(filename, **options)
    @movie = FFMPEG::Movie.new(filename)
    reset(**options)
    end

    def reset(**options)
    @frames = []
    @tmp_dir = options[:tmp_dir] || DEFAULT_OPTIONS[:tmp_dir]
    @resolution = options[:resolution] || DEFAULT_OPTIONS[:resolution]
    @duration = options[:duration] || DEFAULT_OPTIONS[:duration]
    end

    def logger
    FFMPEG.logger
    end

    def logger=(logger)
    FFMPEG.logger = logger
    end

    def screenshot(path, **options)
    @movie.screenshot(path, resolution: resolution, **options)
    end

    def ensure_output_directory
    FileUtils.mkdir_p(tmp_dir)
    end

    def to_animation(output_file = "result.gif")
    ensure_output_directory unless File.exist?(tmp_dir)
    each_duration do |second|
    path = "#{tmp_dir}#{second}.png"
    begin
    screenshot(path, seek_time: second)
    ensure
    frames << path
    end
    end
    Magick::ImageList.new(*frames).coalesce.write(output_file)
    ensure
    FileUtils.rm(Dir.glob(File.join(tmp_dir, "*")))
    end
    alias to_anime to_animation

    def each_duration(&block)
    if @duration.respond_to?(:call)
    @duration.call @movie
    else
    @duration.instance_of?(Range) ? @duration.each : @duration.times
    end.each(&block)
    end
    end