5

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

4

2 回答 2

9

用于combine_options同时将gravitycrop选项传递给 ImageMagick 的mogrify实用程序:

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

您还应该避免直接在视图中处理变体,因为它会阻止渲染。

于 2018-04-05T20:53:53.077 回答
0

您需要在某处添加重力设置。在命令行中,它将是 -gravity center。

范围扩展了画布,我认为您不需要

尝试:

gravity: "center", crop: "800x800"
于 2018-04-05T17:23:40.710 回答