Carrierwave Crop Specific Version

Carrierwave Cropping

You can do something like this:

process :cropper

def cropper
manipulate! do |img|
if model.crop_x.blank?
image = MiniMagick::Image.open(current_path)
model.crop_w = ( image[:width] * 0.8 ).to_i
model.crop_h = ( image[:height] * 0.8 ).to_i
model.crop_x = ( image[:width] * 0.1 ).to_i
model.crop_y = ( image[:height] * 0.1 ).to_i
end
img.crop "#{model.crop_w}x#{model.crop_h}+#{model.crop_x}+#{model.crop_y}"
end
end

I'm running code equivalent to that in one of my apps.

How to crop image on upload with Rails, Carrierwave and Minimagick?

I have understood.

  version :thumb do    
process resize_to_fit: [300, nil]
process crop: '300x150+0+0'
#process resize_and_crop: 200
end

private

# Simplest way
def crop(geometry)
manipulate! do |img|
img.crop(geometry)
img
end
end

# Resize and crop square from Center
def resize_and_crop(size)
manipulate! do |image|
if image[:width] < image[:height]
remove = ((image[:height] - image[:width])/2).round
image.shave("0x#{remove}")
elsif image[:width] > image[:height]
remove = ((image[:width] - image[:height])/2).round
image.shave("#{remove}x0")
end
image.resize("#{size}x#{size}")
image
end
end

resize_and_crop from here:

http://blog.aclarke.eu/crop-and-resize-an-image-using-minimagick/

Is it possible to recreate only specific versions with carrierwave?

It seems like you can pass an argument to recreate_versions! to specify which versions to recreate.

You might come to a situation where you want to retroactively change a version or add a new one. You can use the recreate_versions! method to recreate the versions from the base file. This uses a naive approach which will re-upload and process the specified version or all versions, if none is passed as an argument.

I had the same question actually, because I thought you couldn't do this, but it turns out you can.

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

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



Related Topics



Leave a reply



Submit