Creating image buttons with Ruby and RMagick

Create button-like thingies with Ruby and RMagick

Below is a simple script that saved me some time – for various reasons I had to replace horrid image buttons used on a web site with more compliant-looking image buttons. You could get buttons that look exactly like this via CSS, but in this case swapping out the images was the easiest fix.

In comes RMagick , the ruby interface to the venerable
ImageMagick graphics library.

First you create the canvas, then you create the Magick::Draw object that you draw onto the canvas. On linux/unix machines you can directly display the image, too via canvas.display.

The script:

#!/usr/bin/env ruby
require 'RMagick'
[
    ['add to basket','buy.gif',100],
    ['change','change.gif',60],
    ['checkout','checkout.gif',75],
    ['continue','continue.gif',75],
    ['continue shopping','continue_shopping.gif',130],
    ['go','go.gif',30],
    ['next','next.gif',45],
    ['place order','place_order.gif',90],
    ['previous','previous.gif',70],
    ['product list','product_list.gif',90],
    ['update','recalculate.gif',60],
    ['submit','submit.gif',60],
    ['update','update.gif',60],
    ['please wait','wait.gif',90]
].each{|button|
    canvas=Magick::Image.new(button[2],25){
        self.background_color='#BED8F1'
    }
    d=Magick::Draw.new
    d.stroke('transparent')
    d.fill('black')
    d.font='/var/lib/defoma/x-ttcidfont-conf.d/dirs/TrueType/Verdana_Bold.ttf'
    d.pointsize=11
    d.font_weight=Magick::BoldWeight
    d.text(0,0,button[0])
    d.text_antialias(false)
    d.font_style=Magick::NormalStyle
    d.gravity=Magick::CenterGravity
    d.draw(canvas)
    canvas=canvas.raise(3,3)
    # canvas.display
    canvas.write(button[1])
}

The result:














Saved me some time, and I learned a bit out Rmagick in the process.

Get the script here

Recommend me on Working With Rails

Add to Technorati Favorites

Add to Google