Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a cropped and centered image with Imagemagick's command line options with variant?

I have a Ruby on Rails 5.2 RC2 app that uses ActiveStorage for hosting images. In particular it's transforming images with variant.

I would like to pass an image, typically of 16:9 or 4:3 ratio and have variant crop it to a specific ratio, width x height, and have it centered. The image could be horizontal or vertical, but the new cropped size is centered.

Image Cropping

From the Imagemagick Command Line Options documentation, I have the following:

<%= image_tag @photo.image.variant(extent: "1:1", crop: "800x800").processed.service_url %>

It creates a square crop, but it's not centered. It defaults to the left. How do I create a cropped image that's centered with Imagemagick's command line option?

I'm looking for a solution that should work on any image size or aspect ratio. I believe any resizing works off of the originally uploaded image for creation.

For reference, I'm looking to upgrade an older Rails app that uses Carrierwave. There is a resize_to_fill that does exactly that. Example code:

version :square_thumb do process :resize_to_fill => [200,200] end

like image 631
spong Avatar asked Apr 05 '18 17:04

spong


1 Answers

Use combine_options to pass the gravity and crop options to ImageMagick’s mogrify utility simultaneously:

@photo.image.variant(combine_options: { gravity: "center", crop: "800x800" })

You should also avoid processing the variant directly in the view, as it blocks rendering.

like image 54
George Claghorn Avatar answered Nov 13 '22 22:11

George Claghorn