Search code examples
ruby-on-railspaperclipcroptemporary-filesjcrop

How to crop a temp image with Paperclip and store it in Amazon S3 in Rails 3


I'm having a great trouble trying to do some out-of-ordinary tricks with paperclip. This is my situation: My app users have an avatar image and my idea is to let them crop their avatars through Jcrop. My app is hosted in Heroku so that I must to upload the images to Amazon S3. I've used this popular railscast to implement the cropping functionality but it requires to process two times the images. Here is where the problems started.

I think than a posible solution might be not process the images in the first time (when the user selectes an image) but do it the second. I've implemented this code in my controller:

    def change_avatar
      @user = current_user
      paperclip_parameters = params[:user][:avatar] #first time call

      if @temp_image_object.present? || params[:avatar].present?
        if check_crop_params  #second controller call
          @user.avatar = File.new(@user.tmp_avatar_path) #overrides the 
          redirect_to @user, notice: t("messages.update.user.avatar") if @user.save
        else    #first controller call
          @temp_path = @user.generate_temp_image(paperclip_parameters)
          @user.tmp_avatar_path = @new_path #store the custom path to retrieve it in the second call
          render :action => 'avatar_crop' if @user.save
        end
      end
    end

    def check_crop_params
      !params[:user][:crop_x].blank? && !params[:user][:crop_y].blank? && !params[:user][:crop_w].blank? && !params[:user][:crop_h ].blank?
    end

and in my user model:

  #this method copies the original image tempfile when user upload the image to a custom path and returns the custom path
  def generate_temp_image(paperclip_parameters)
    uploaded_img_path = uploaded_img.tempfile.path

    temp_dir = Rails.root.join('public/tmp')
    Dir.mkdir(temp_dir) unless Dir.exists?(temp_dir)

    FileUtils.cp(uploaded_img.tempfile, temp_dir)

    new_path = uploaded_img_path
  end

I also have the custom processor for jcrop, that takes the crop variables when proccessing the images. When I upload an image (first controller call) the change_avatar method works well but when I crop the image (second controller call) the image isn't cropped, paperclip creates the image styles files but ignores the cropping I did.

Any ideas? what I should do?


Solution

  • I had forgotten an small detail.. looking in the server logs I realized that the paperclip process wasn't cropping the images, so I looked in my custom processor and I find that it depended on the crop parameters : crop_x, crop_y, crop_w, crop_h. For some reason this parameters didn't reach the processor, so the images never were going to be cropped. All I had to do is to manually assign this params to the user vars, and it works!