Books by Jules J. Berman, covers

EXTRACTING A SECTION OF AN IMAGE IN RUBY


Ruby is a free, open source, object-oriented programming language. There are many beginner books on Ruby. If you work in the medical or biological fields, you might want to try my book, Ruby Programming for Medicine and Biology, which will be published in the early fall, 2007, by Jones & Bartlett Publishers.

We have previously described what you need to install to manipulate images in Ruby (ImageMagick, RMagick, and Tcl/Tk). Here is a short Ruby script that shows how to use RMagick (Ruby's interface to ImageMagick) to modify and display an image.


#!/usr/local/bin/ruby
#leaf3.rb
#
#This Ruby script was created by Jules J. Berman on 7/8/2007
#and is provided as a public domain document
#
#The software is provided "as is", without warranty of any kind,
#express or implied, including but not limited to the warranties
#of merchantability, fitness for a particular purpose and
#noninfringement. in no event shall the authors or copyright
#holders be liable for any claim, damages or other liability,
#whether in an action of contract, tort or otherwise, arising
#from, out of or in connection with the software or the use or
#other dealings in the software.
#
require 'RMagick'
include Magick
orig_leaf = ImageList.new("leaf.jpg").resize!(0.4)
orig_leaf.write("orig.gif")
leaf = ImageList.new("leaf.jpg").first.crop(50, 310, 300, 300).resize!(0.4)
leaf.write("new.gif")
require 'tk'
root = TkRoot.new {title "view"}
TkButton.new(root) do
  image TkPhotoImage.new{file "orig.gif"}
  command {exit}
  pack
end
TkButton.new(root) do
  image TkPhotoImage.new{file "new.gif"}
  command {exit}
  pack
end
Tk.mainloop
exit




The figure below displays a jpeg image of a leaf (obtained from Wikipedia as a public domain file: http://en.wikipedia.org/wiki/Image:Leaf_1_web.jpg, and renamed leaf.jpg for this page).

Rights annotation from Wikipedia:"This image from PD Photo.org has been released into the public domain by its author and copyright holder, Jon Sullivan."

The image of the leaf sits atop the same image, modified by the "crop" method, which extracts a section of the image. The example sends the criop method to the image object, with arguments (50, 310, 300, 300).

The syntax of the crop method is: crop(x, y, width, height)

x and y are the offsets from the upper left corner of the image.


Viewing a a modified JPEG image in Ruby


More on creating and displaying images in Ruby

Last modified July 8, 2007