class Utils::Collage

Public Class Methods

new(small_width, small_height, collage_width, collage_height, num_images) click to toggle source
# File lib/fccc/utils.rb, line 13
def initialize(small_width, small_height, collage_width, collage_height, num_images)
  # Size of each image in collage in pixel
  @small_width = small_width
  @small_height = small_height
  # Number of columns and rows of a collage
  @collage_width = collage_width
  @collage_height = collage_height
  @num_images = num_images
  Utils.load_credentials(CREDENTIALS_PATH)
end

Public Instance Methods

create_collage(output_path) click to toggle source
# File lib/fccc/utils.rb, line 47
def create_collage(output_path)
  # Create collage
  puts "Creating collage..."
  # Prepare a base image
  @collage = Magick::Image.new(@small_width * @collage_width, @small_height * @collage_height) do
    self.background_color = "black"
  end
  # Add rectangularly resized images to the base image
  @images.each_with_index do |img, idx|
    @collage.composite!(img.resize_to_fill!(@small_width, @small_height),
                       @small_width * (idx % @collage_width),
                       @small_height * (idx / @collage_width),
                       Magick::OverCompositeOp
                      )
  end
  # Save collage to a designated path
  @collage.write(output_path)
  puts "Collage saved to #{output_path} ."
end
download_images_by_keywords(keywords) click to toggle source
# File lib/fccc/utils.rb, line 24
def download_images_by_keywords(keywords)
  # Get image url for each keyword
  img_urls = Array.new()
  keywords.each do |kw|
    # Apparently no image without keyword
    kw.nil? ? img = nil : img = flickr.photos.search(text: kw, per_page: 1)[0]
    while img.nil? do
      # Randomly pick an English word and search top-rated image for the word
      puts "*** Image for '#{kw}' not found. Trying a randomly picked word. ***"
      kw = RandomWord.nouns.next.strip
      img = flickr.photos.search(text: kw, per_page: 1)[0]
    end
    url = FlickRaw.url(img)
    puts "Image for '#{kw}' => #{url}"
    img_urls.push(url)
  end
  # Download images
  puts "Downloading images..."
  @images = img_urls.map do |url|
    Magick::Image.read(url).first
  end
end