Need random sample images? Why not imgur?
July 4, 2012 in Ruby on RailsThe 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.
- The gallery contains the awesomest images.
- It is regularly updated.
- The images aren’t likely to cause copyright issues.
- Imgur is extremely robot-friendly. See for yourself:
How to download images from imgur’s gallery in Ruby
require 'json'
require 'open-uri'
gallery = JSON.parse(open('http://imgur.com/gallery.json').read)['gallery']
# construct URLs
gallery.each {|i| i['url'] = "http://imgur.com/#{i['hash']}#{i['ext']}" }
# select images that aren't too big
gallery.select {|i| i['size'] < 200_000 }
# or images that aren't too small
gallery.select {|i| i['width'] > 400 && i['height'] > 400 }
# select only PNG images
gallery.select {|i| i['ext'] == '.png'}
# use images in Carrierwave https://github.com/jnicklas/carrierwave
# (because Carrierwave can download images out-of-the-box; otherwise you'd have to
# download the image and attach it as a file)
Post.create!(
:remote_image_url => gallery.sample['url'],
:title => Faker::HipsterIpsum.words(4),
:text => Faker::HTMLIpsum.body
)
Isn’t life great?
Liked the post? Treat me to a coffee