Skip to content

Instantly share code, notes, and snippets.

@aanand
Created November 23, 2011 11:39
Show Gist options
  • Save aanand/1388486 to your computer and use it in GitHub Desktop.
Save aanand/1388486 to your computer and use it in GitHub Desktop.
Command-line gif creator
#!/usr/bin/env ruby
require "optparse"
default_file_pattern = "png/*.png"
default_output_filename = "out.gif"
start = nil
finish = nil
skip = 1
convert_args = nil
output_filename = default_output_filename
opts = OptionParser.new do |opts|
opts.banner = <<EOB
Usage: gif [OPTIONS] [FILES...]
Creates a looping animated gif out of FILES (which defaults to #{default_file_pattern.inspect}).
Uses ImageMagick's `convert' command, which must be present on your $PATH.
You can extract frames from a movie using mplayer:
mplayer -ao null -vo png:outdir=png FILE
To speed up extraction, specify a start time and duration for the segment you want using -ss and -endpos.
To start at 1m20s and extract 15 seconds:
mplayer -ao null -vo png:outdir=png -ss 0:1:20 -endpos 15 FILE
Options you can pass to `gif':
EOB
opts.on "--start N", "Start at frame N", Integer do |v|
start = v
end
opts.on "--finish N", "Finish at frame N", Integer do |v|
finish = v
end
opts.on "--skip N", "Only use every Nth frame", Integer do |v|
raise OptionParser::InvalidArgument, "must be at least 1" unless v >= 1
skip = v
end
opts.on "--convert ARGUMENTS", "Arguments to pass to convert (useful ones: '-crop WxH+X+Y!', '-resize WxH', '-delay N')" do |v|
convert_args = v
end
opts.on "--output FILENAME", "Filename to save gif to (defaults to #{default_output_filename.inspect})" do |v|
output_filename = v
end
end
begin
opts.parse!
rescue OptionParser::ParseError => e
puts e.message
puts
puts opts
exit -1
end
all_files = ARGV
all_files = Dir.glob(default_file_pattern) if all_files.empty?
files = []
idx = start || 0
finish = finish || all_files.length
while idx < finish
files << all_files[idx]
idx += skip
end
components = ["convert"]
components += convert_args.split(" ") if convert_args
components += ["-loop", "0"]
components += files
components += [output_filename]
cmd = components.join(' ')
puts(cmd)
system(cmd)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment