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) {
jQuery(‘#coords_x’).val(c.x);
jQuery(‘#coords_y’).val(c.y);
jQuery(‘#coords_x2’).val(c.x2);
jQuery(‘#coords_y2’).val(c.y2);
jQuery(‘#coords_h’).val(c.h);
jQuery(‘#coords_w’).val(c.w);
};

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

def crop_image
image = Image.find params[:id]
image_list = Magick::ImageList.new(open(image.attachment.to_file(:original)))
cropped_image = image_list.crop(x.to_f, y.to_f, w.to_f, h.to_f)
cropped_image.write(‘tmp_filename’)
image.attachment = File.open ‘tmp_filename’
image.save
File.delete ‘tmp_filename’
..
end

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.

Leave a comment