/ RAILS

Ruby draw line on image using RMagick

In Ruby draw line on image, draw circle on image/ various shapes can be drawn using RMagick gem. To install RMagick gem you need to add RMagick in Gemfile

rmagick

Add RMagick in Gemfile

gem 'rmagick'

Source: Github/RMagick

Install the Gem

Bundle the Rails project to install rmagick if not already installed

bundle install

After successful installation of RMagick gem you are ready to use RMagick features in your Rails Project

Steps

1. Create Image Object

To Draw something on a image, you need to create image object in Rails as follows,

image = Magick::Image.read('image-url-with-extension').first

Then you will have image object with variable image

2. Create Draw object

You need to create draw object as follows,

gc = Magick::Draw.new

This will create new draw object through which you can draw various shapes on canvas.

3. Draw on Canvas

Define colour need to be used to draw on canvas by following command,

gc.stroke('red')

The above command will set color with which drawing will happen

4. Draw Line on Canvas

gc.line(x1, y1, x2, y2)

The above command will draw line from point (x1, y1) to point (x2, y2)

Similarly you can draw line, circle — various shapes using object of Magick::Draw.new here gc.

Finally you need to impose canvas on image as,

gc.draw(image)

The above command imposes whatever on canvas onto image.

5. Write Image file

You can write the image file on your file system using following command,

image.write('divided.gif')

This will write image in current location of your project.

References

You can refer for more available methods with draw RMagick documentation which can well be used with Ruby. Feel free to comment if you face any problem while using RMagick with Ruby. Documentation will also help you with how to use RMagick gem for Image Manipulation with Ruby.

akshay

Akshay Mohite

Hi there! I am a Ruby on Rails & ReactJS Enthusiast, building some cool products at DTree Labs.

Read More
Buy me a coffee