#! /usr/bin/ruby # == Synopsis # Ruby script to animate a directory of images. # Requires gifsicle and convert (ImageMagick) # # == Usage # ruby animate.rb [ -h | --help ] [ -c | --clobber ] dir output.gif [ type ] # # dir:: # Directory will be expanded internally. # type:: # Filetype of input images (default .png) # clobber:: # Overwrite an existing output file. # # == Author # Matt Foster # # == Bugs # Probably. # Should take a glob instead of a directory as an argument. # # == Copyright # Copyright (c) 2006 Matt Foster # Licensed under the same terms as Ruby. require 'optparse' require 'rdoc/usage' DELAY = 100 # Delay time between frames 1/100 s. COLS = 256 # Colours in animation. DISP = true # Debug switch. clobber = false TYPE = '.png' # Default image type. def progTest(prog) out = %x{which #{prog}} if out.length == 0 $stderr.puts "Missing program #{prog}" false else true end end if __FILE__ == $0 opts = OptionParser.new opts.on("-h", "--help") { RDoc::usage } opts.on("-c", "--clobber") { clobber = true } opts.parse!(ARGV) rescue RDoc::usage('usage') dir = ARGV.shift || nil out = ARGV.shift || nil type = ARGV.shift || TYPE type = '.' + type unless type[0...1] == '.' # Test for programs we need to continue if progTest('convert') == false || progTest('gifsicle') == false puts 'gifsicle lives at: http://www.lcdf.org/gifsicle/' puts 'ImageMagick lives at: http://www.imagemagick.org/' exit end if dir == nil || out == nil RDoc::usage('usage') exit end if File.exist?(out) if clobber begin File.unlink(out) rescue $stderr.puts "Problem removing old output file" + $! end else puts "File #{out} exists" exit end end dir = File.expand_path(dir) files = Dir["#{dir}/*#{type}"] if DISP puts "Processing #{files.length} #{type} files in #{dir}" end files.each do |file| # Convert to gif print '.' if DISP system("convert -trim #{file} #{File.basename(file, type)}.gif") end print("\n") if DISP gifs = Dir["#{dir}/*.gif"] # Animate with gifsicle system("gifsicle --colors #{COLS} -O2 --delay #{DELAY} #{gifs.join(' ')} > #{out}.tmp") begin gifs.each {|f| File.unlink(f)} File.rename("#{out}.tmp", out) rescue Errno::EEXIST $stderr.puts "Output file aready exists" + $! rescue $stderr.puts "Problem unlinking/renaming files" + $! end puts 'Completed' if DISP end