Saturday, February 27, 2010

Dynamic Image from text/string in Rails

Image will be generated dynamically from string or text:

Use - require 'RMagick' in your class

def draw_image
#Image parameters
options = {:img_width => 300, :img_height => 250, :text_color => "#FF0000", :font_size => 36,
:text => "This is text", :bg_color => "#EFEFEF"}
#Initialize a container with it's width and height
container=Magick::Image.new(options[:img_width],options[:img_height]){
self.background_color = options[:bg_color]
}
#Initialize a new image
image=Magick::Draw.new
image.stroke('transparent')
image.fill(options[:text_color])
image.font='/var/lib/defoma/x-ttcidfont-conf.d/dirs/TrueType/Verdana_Italic.ttf'
image.pointsize=options[:font_size]
image.font_weight=Magick::BoldWeight
image.text(0,0,options[:text])
image.text_antialias(false)
image.font_style=Magick::NormalStyle
image.gravity=Magick::CenterGravity
#Place the image onto the container
image.draw(container)
container=container.raise(3,1)
# To test the image(a pop up will show you the generated dynamic image)
container.display
# generated image will be saved in public directory
#container.write("public/image.gif")
end
view raw gistfile1.txt hosted with ❤ by GitHub


Pre-requisite : You must have rmagick and Imagemagick installed.
Details: http://www.simplesystems.org/RMagick/doc/draw.html

3 comments: