ruby-on-railsimagecroprails-activestoragevips

How to crop images at the center with Rails 7 Active Storage and Vips?


I successfully setup Rails 7 and Active Storage with the Vips library to upload images and now I would like to have a squared image variation with dimensions of 400x400px that is cropped at the center, regardless of the uploaded image.

For example, given a user upload a 1200x1600 px or 200x800 px image, the squared image variant should have dimensions of 400x400px cropped at the center, possibly without any added "alpha channel" but just the information contained in the original image (image enlargement or shrinking should be automatic and the image should not be distorted).

I searched the Web without success. The following code in my model just crops the image not at the center and it doesn't "zoom in" the image when one dimension is lower than 400 px:

class User < ApplicationRecord
    has_one_attached :picture do |attachable|
      attachable.variant(
        :thumb, 
        :crop => [0, 0, 400, 400], 
        :resize_and_pad => [400, 400, :gravity => 'centre']
      )
    end
end

Any help?


Solution

  • I think, this is what you're looking for:

    has_one_attached :picture do |attachable|
      attachable.variant :thumb, resize_to_fill: [400, 400]
    end
    

    https://edgeguides.rubyonrails.org/active_storage_overview.html#transforming-images


    Resized, squared and cropped in the center:

    it's a picture