Ruby glob example - preview many image by creating a single HTML file

Every once in a while someone will give me a large collection of images (JPG, PNG, GIF) that I need to either look at or print. On the Mac (and recent versions of Windows) there are now tools to look at a group of images, but I still like a little program that I wrote.

I wrote this program in Ruby, and what it lets you do is combine all of your pictures into one web page. Then, with the use of CSS, the HTML document you create lets you print each image on a separate page.

A few cool things about the program: it uses a heredoc to hold a multiline string; it uses the glob method of the Dir class to generate a list of all JPG image files in the current directory; and it's a pretty concise program that does a lot of work.

With that introduction, here is the source code for this Ruby program.

# merge.rb

# use a here doc (heredoc) to hold our header string
<style type="text/css">
  P.breakhere {page-break-before: always}


# use the Dir glob method to get all jpg image files
Dir.glob("*jpg").each { |file|
  puts "<img src=\"#{file}\" border=\"0\">"
  puts "<P class=\"breakhere\">"

To use the program as it's shown you'll want to copy this program into a directory that has all of your image files. Assuming this file is named merge.rb these files are all JPG images you can run the program like this:

ruby merge.rb > my_images.html

This creates a new file named my_images.html. When you look at it in a browser all of the images will appear consecutively, but then when you fire up the "print preview" command you'll see that each image will be printed on a separate page.

Also note that you can easily change the "jpg" reference in the program to "png" or "gif" to make a single page that contains images of these types.