🤖🚫 AI-free content. This post is 100% written by a human, as is everything on my blog. Enjoy!

Need random sample images? Why not imgur?

July 4, 2012 in Ruby on Rails

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('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?

Buy me a coffee Liked the post? Treat me to a coffee