Skip to content

Instantly share code, notes, and snippets.

@dmerrick
Created June 5, 2012 17:09
Show Gist options
  • Save dmerrick/2876282 to your computer and use it in GitHub Desktop.
Save dmerrick/2876282 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby -w
require 'open-uri'
require 'digest/md5'
require 'fileutils'
# this script creates a gif from NASA's high-res images of the sun
# the goal is to capture the transit of Venus in gif form
# it is expected that this will be run on OS X
# the following are required:
# [sudo] [brew|port] install imagemagick
# [sudo] [brew|port] install gifsicle
class TransitOfVenus
URL = "http://sdo.gsfc.nasa.gov/assets/mov/depot/APOD/latest_APOD_HMIC_FR.jpg"
OUT = File.join(ENV['HOME'], "Desktop", "venus")
TMP = File.join(OUT, "tmp")
class << self
# where the magic happens
def run!
save_current_image
convert_jpg_to_gif
if they_are_different?
combine_the_gifs
else
clean_up_the_duplicate_image
end
end
def save_current_image
puts "saving the current image"
image_file = "#{Time.now.to_i}.jpg"
FileUtils.mkdir_p(TMP)
open(File.join(TMP, image_file), 'wb') do |local_file|
local_file << open(URL).read
end
end
def convert_jpg_to_gif
puts "converting the jpg to a gif..."
images = Dir.glob(File.join(TMP, "*.jpg")).sort
images.each do |image|
filename = File.basename(image).split('.')[0]
output = "#{filename}.gif"
`convert #{File.expand_path(image)} #{File.join(TMP, output)}`
puts "removing the original jpg"
File.delete(File.expand_path(image))
end
end
def they_are_different?
puts "checking for differences"
all_converted_images = Dir.glob(File.join(TMP, "*.gif")).sort
return true if all_converted_images.count < 2
penultimate, ultimate = all_converted_images[-2,2].map do |image|
Digest::MD5.hexdigest(File.read(image))
end
if penultimate == ultimate
puts "current image is the same as previous image"
return false
else
puts "new image found"
return true
end
end
def combine_the_gifs
puts "making the final gif..."
gifname = "#{Time.now.to_i}.gif"
gifpath = File.join(OUT, gifname)
`gifsicle --delay=10 --loop #{TMP}/*.gif > #{gifpath}`
puts "saved final gif as #{gifpath}"
end
def clean_up_the_duplicate_image
puts "removing the duplicate image"
duplicate_image = Dir.glob(File.join(TMP, "*.gif")).last
File.delete(duplicate_image)
end
def wait(minutes)
minutes.downto(1).each do |n|
s = n == 1 ? nil : "s"
puts "sleeping for #{n} minute#{s}..."
sleep 60
end
end
end
end
if $0 == __FILE__
loop do
TransitOfVenus.run!
TransitOfVenus.wait(10)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment