Monday, February 25, 2008

A local Ruby script example with fileutils, open-uri, rmagick and mysql

##################################
# a code example for writing a ruby script to be running locally
# to do some regular local jobs such as:
# 1, download files or images from Internet
# 2, local file operations like mkdir, cp and remove
# 3, access or store data into local database like mysql
# 4, image resizing or cropping using image-magick
##################################
require 'open-uri'
require 'fileutils'
require 'RMagick'
require 'mysql'

# init local directories
FileUtils.mkdir_p "original/montreal"
FileUtils.mkdir_p "thumbnailed/montreal"

# init the database access
db = Mysql::new('127.0.0.1', 'root', '12345', 'test')

# init links to Internet
base_url = "http://farm1.static.flickr.com/"
image_urls = ['40/123180238_552597a079_b.jpg',
'146/390735501_54f0b2e826_b.jpg',
'50/131278273_4ce6400bfa_b.jpg']

# create a table to store image names
db.query("DROP TABLE IF EXISTS images")
db.query("CREATE TABLE images (name VARCHAR(64))")
image_urls.each do |image|
db.query("INSERT INTO images (name) VALUES ('#{image}')")
end

# download images from Internet
for i in 0..2
open("original/montreal/#{i}.jpg", 'wb').write(open("#{base_url}#{image_urls[i]}").read)
end

# resize and crop images
for i in 0..2
image = Magick::Image.read("original/montreal/#{i}.jpg").first
image.crop_resized!(150, 150, Magick::NorthGravity)
image.write("thumbnailed/montreal/#{i}.jpg")
end
References:

Ruby MySQL: http://www.tmtm.org/en/mysql/ruby/
RMagick: Making thumbnails with RMagick
FileUtils: http://www.ruby-doc.org/stdlib/libdoc/fileutils/rdoc/index.html
Ruby OpenURI: http://www.ruby-doc.org/core/classes/OpenURI.html

1 comment:

Anonymous said...

If I'm not mistaken,

open(fn, 'wb').write(whatever)

leaves the output file open.

You probably want

open(fn, 'wb') do |f|
  f.write whatever
end

That returns control to the open function after the block ends, allowing it to close the file.