Cropping Images With Carrierwave and Jcrop


Recently I followed Ryan Bates’s episode for cropping images with carrierwave and Jcrop. Everything worked well except the cropped images are a bit blurry. 

The reason is that I am using resize_to_limit(300,30000) to make the cropped area proportional to the image size I displayed in the view, which I have the css to be width:300px;

This will lower the quality of the cropped image since the original image is often bigger than 300px , in my case somewhere around 500px x 600px.

It turned out that I just needed to do a bit arithmetic to avoid this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def crop
  if model.crop_x.present?
    # resize_to_limit(300, 3000)
    manipulate! do |img|
      converted_h = 300.0*img.rows/img.columns
      x = (model.crop_x.to_i/300.0*img.columns).to_i
      y = (model.crop_y.to_i/converted_h*img.rows).to_i
      w = (model.crop_w.to_i/300.0*img.columns).to_i
      h = (model.crop_h.to_i/converted_h*img.rows).to_i
      # img.crop("#{w}x#{h}+#{x}+#{y}")
      img.crop!(x, y, w, h)
      img
     end
  end
end

img.columns and image.rows return the with and height of the original image. We need to scale the crop ratio with respect to 300px in order to crop the correct portion of the original image without lossing resolution.

« Modal Sign-In Form With Twitter Bootstrap 3 and JQuery Validation