Graphics and other File type handling in Ruby

Ruby does not have native support for image manipulation and relies on C Libraries such as ImageMagick and GraphicsMagick. There is RMagick that provides an interface against ImageMagick and GraphicsMagick.

RMagick is available as a part of installation RMagick gem. Example of RMagick usage is shown below.

require ‘rubygems’
require ‘RMagick’

img = Magick::Image.read(‘image.jpg’).first
thumb = img.resize(100,100) //Width, Height
thumb.write(‘image-thumb.jpg’)

RMagick has other methods for resizing an image to smaller sizes such as: img.scale, img.sample, img.thumbnail

There is an alternative to image resize which is image cropping. Image cropping can be accomplished with the help of img.crop method.

thumb = img.crop(x,y,width,height)
thumb = img.crop(Magick::WestGravity,x,y,width,height)
thumb = img.crop(Magick::EastGravity,width,height)

Ruby RMagick allows you to add text to your images such as caption or copyright with the help of annotate method. In addition, RMagick can help you to convert one image type form another with the help of write or format methods.

Another use of Ruby graphics management is conversion of data into graphs such as pie charts, bar charts, and other type of graphs. In order to draw these graphs, we need to employ Gruff library.

p.Gruff::Pie.new
p.theme_monochrome
p.title = “My Pie Chart”
p.data(‘5’,[21])
p.data(‘12’,[45])
p.write(‘my-chart.png’)

Featured pages

Ruby

Set of Ruby Object Oriented Programming Language tutorials that cover such topics as Ruby strings, …

Rails

Rails Framework tutorial teaches you how to utilize de facto framework of choice for Ruby developme…

Ruby Duck Typing

“If an object quacks like a duck just go ahead and treat it as a duck” – this fun…

Regular Expressions

Ruby uses the =~ operator to check any given string against regular expression. For example, a stri…

Credit Card Number

Every last digit of any credit card is a check sum digit that is determined by all digits in front …

Ruby Arrays

Ruby Programming Language has built in support for Arrays. Arrays help you define some of the compl…

Ruby Hashes

Hashes are very similar to arrays in Ruby and hashes interface is similar to Ruby array interface. …

Ruby Code Block

Ruby is very unique language when it comes to code blocks. You can simply pass a code block to a me…