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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With