Class: Utils::Collage

Inherits:
Object
  • Object
show all
Defined in:
lib/fccc/utils.rb

Instance Method Summary collapse

Constructor Details

#initialize(small_width, small_height, collage_width, collage_height, num_images) ⇒ Collage

Returns a new instance of Collage.



13
14
15
16
17
18
19
20
21
22
# 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

Instance Method Details

#create_collage(output_path) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# 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) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# 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