aviemet
aviemet

Reputation: 1653

Pass values into Carrierwave ImageUploader

My DB has an Images table which belongs to a Users table. I'm using a JS library to crop and upload images, which sends the cropping coordinates as parameters to the controller. (I'm using croppic)

In my Images controller

def crop_upload
    uploader = ImageUploader.new
    if uploader.store!(params[:img])
        @image = Image.new
        @image.href = uploader.url
        render :json => {
            :status => 'success',
            :url => uploader.url,
            :width => SETTINGS[:images][:full][:width], 
            :height => SETTINGS[:images][:full][:height]
        }
    else
        render :json => { :status => 'error', :message => "Oops" }
    end
end

The params object also has a bunch of info like x, y coordinates and crop widths which need to be passed to the Carrierwave ImageUploader object in order that it can crop properly, but I can't see any way to get them there.

In my Uploader, I the variables model and file, which according to the documentation should have values, are empty. I tried passing in values using instance variables (@image.params = ...), but the model variable is empty.

Upvotes: 0

Views: 772

Answers (1)

knutsel
knutsel

Reputation: 1291

Store the crop information on the model (in attr_accessors if you dont want to actually store the data).

Then in the carrierwave uploader use model.crop_x where crop_x is your attribute, to access these values.

We use this in combination with cloudinary to not actually crop the original image but serve a cropped version on the fly. However this will also work if you want to crop the image server side and store the result.

example:

version :cropped do
  process :custom_crop
  process convert: 'jpg'
end

def custom_crop
  {
    x: model.public_send("#{crop_field_prefix}_x"),
    y: model.public_send("#{crop_field_prefix}_y"),
    width: model.public_send("#{crop_field_prefix}_w"),
    height: model.public_send("#{crop_field_prefix}_h"),
    crop: :crop
  }
end

As you can see in this example the attributes we store the crop information in are dynamic but that is overkill in most situations and directly calling model.crop_x should suffice

Upvotes: 1

Related Questions