Ruby RMagick Thumbnails

Demonstration script for using RMagick to generate thumbnails on demand to send to the browser. 

Ruby Script Library

Our Ruby scripts are all compatable with GoDaddy.com Deluxe hosting. Also see our GoDaddy Ruby Tutorial.

Ruby RMagick Thumbnail Generator - Tested for use with GoDaddy.

#!/usr/local/bin/ruby -w
# thumbnail.cgi

require "cgi"
require "rubygems"
require "RMagick"

$cgi = CGI.new

pic = ""

if $cgi.has_key?('pic')
pic = $cgi['pic']
end

img = Magick::Image::read(pic).first
thumb = img.scale(200, 200)
puts "Content-Type: image/jpeg\n\n"
puts thumb.to_blob


First, you must always begin by telling your script where Ruby is. Then you require cgi to get the user's input. With GoDaddy you must require "rubygems" before you can import any gem. $cgi is a new CGI object, which is used to get the desired file path. For example "/pictures/me.jpg" will get the picture called me.jpg in the /pictures/ folder. You must use the if here, otherwise you will get an error. An alternative to pic = "" through end is:

pic = ($cgi.has_key?('pic') ? pic = $cgi['pic'] : "")

 

Which uses the strange ? : if notation. After you find out which picture to shrink, you read it into the img object, scale it, then use to_blob to print the image to the browser.

Back to the Homepage of the Ruby Script Library