Need random sample images? Why not imgur?

July 4, 2012 imgur Ruby

The other day I had to pre-populate an application with some illustrations. For random text I would use ffaker, and for images of a particular size I would likely use placekitten, but there is no trivial method to produce some random images for your seed database. And of course I did not want to collect the images by hand.

Guaranteed to be random

I discovered that you can get a good array of images from the Imgur Gallery.

require 'json'
require 'open-uri'

gallery = JSON.parse(open('').read)['gallery']

# construct URLs
gallery.each {|i| i['url'] = "{i['hash']}#{i['ext']}" }

# select images that aren't too big {|i| i['size'] < 200_000 }
# or images that aren't too small {|i| i['width'] > 400 && i['height'] > 400 }

# select only PNG images {|i| i['ext'] == '.png'}

# use images in Carrierwave
# (because Carrierwave can download images out-of-the-box; otherwise you'd have to
# download the image and attach it as a file)
  :remote_image_url => gallery.sample['url'], 
  :title => Faker::HipsterIpsum.words(4), 
  :text => Faker::HTMLIpsum.body

Isn’t life great?

Buy Me a Coffee at