Image cropping using jcrop and imagemagick in rails

Jcrop is a great tool to add image cropping functionality to your web application. It gives you an interface to select an area of any image that  you want to crop. Here we will see how to crop an image using jcrop and imagemagick in a rails application.

To get started, download the javascript and css files and save them in your application. Install imagemagick on your conmputer and then install the rmagick gem.

To crop an image, lets first display it in the browser


Bind jCrop onto it.

jQuery(function() {
jQuery(‘#container img’).Jcrop({
onChange: showCoords,
onSelect: showCoords

Lets say we have a form, which will be used to submit the selected area co-ordinates to our controller action. Jcrop will invoke the callback function(showCoords in this eg.) specified, for the onChange and onSelect events with an object containing the co-ordinates information.

Let us use these values to update the required fields in our form.

function showCoords(c) {

Now on submit, we will use these values to crop the image.

def crop_image
image = Image.find params[:id]
image_list =
cropped_image = image_list.crop(x.to_f, y.to_f, w.to_f, h.to_f)
image.attachment = ‘tmp_filename’
File.delete ‘tmp_filename’

Magick::ImageList also has a rotate method which will take the angle as the argument.

Santhosh Kattissery is a senior consultant at Compassites. He is a web developer with hands on experience in all phases of development, from requirements gathering, database design, development, testing and deployment. He specializes in open source technologies like Ruby on Rails, JQuery, Mongodb & MySql. Prior to Compassites he has worked as a contractor for internet giants like Google and LinkedIn.