Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you crop an image with carrierwave 'after the fact' in rails?

What I'd like to do is upload an image, then take the user to a new page where I will use Jcrop to let the user select the part of the image they want to crop, and then store that image. Essentially, I want to make it a 2-stage process.

I know how to do the javascript part, and I understand the basic flow of how to create this functionality. However, I am not aware of the carrierwave specifics on how to accomplish this.

The closest thing I can find is:

image.recreate_versions!

But I still can't pass in the height/width and starting x,y to crop it.

For example, how can I tell carrierwave to do the cropping 'after the fact' - i.e. not when the image is uploaded for the first time? I see methods to "process" the image, but they happen automatically with fixed Height and Width. How can I delay this?

Essentially, what I'd like to do is define a version dynamically, where I can specify the height and width and x,y

Thanks

like image 435
Fire Emblem Avatar asked May 22 '11 08:05

Fire Emblem


People also ask

What is carrierwave in rails?

This gem provides a simple and extremely flexible way to upload files from Ruby applications. It works well with Rack based web applications, such as Ruby on Rails.


1 Answers

This is the best I can do. There's probably an easier way to do it, but this is my hack:

Here is my 'POST' controller action when the cropping info is passed:

  def update_crop
    @user = User.find(current_user.id)
    @user.crop(params[:x].to_i, params[:y].to_i, params[:h].to_i, params[:w].to_i)

    redirect_to(profile_path, :notice => 'Your profile and avatar was successfully updated.')
  end

Here is the method to add to the User model that contains an "avatar" image uploader:

  def crop(x, y, h, w)
    image = Magick::ImageList.new(avatar.current_path)
    cropped_image = image.crop(x, y, h, w)
    cropped_image.write(avatar.current_path)

    avatar.recreate_versions!
  end

Basically this just hi-jacks the current one, overwrites it, and then tells Carrierwave to create

like image 83
Fire Emblem Avatar answered Sep 28 '22 17:09

Fire Emblem