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’)