conditional convert options paperclip

后端 未结 5 1444
[愿得一人]
[愿得一人] 2021-02-06 09:18

After some research I was able to add styles based on my image_class column.

Model.rb

has_attached_file :image,
                    


        
5条回答
  •  [愿得一人]
    2021-02-06 10:04

    You can also specify convert_options in styles:

    class Image < ActiveRecord::Base
      has_attached_file :image, styles: -> (attachment) { attachment.instance.paperclip_styles }
    
      private
    
      def image_ratio
        # logic to define the image ratio
      end
    
      def paperclip_styles
        vitrina_geometry = image_ratio > 1.2 ? '268x156>' : '268x156^'
        vitrina_convert_options = if image_ratio > 1.2
          "-quality 75 -gravity center -crop '268x156+0+0'"
        else
          "-quality 75 -strip -gravity center -background '#FFFFFF' -extent 268x156"
        end
    
        {
          medium: { 
            geometry: '500x500>',
            convert_options: '-quality 75 -strip'
          },
          thumb: {
            geometry: '256x148>',
            convert_options: '-quality 75 -strip'
          },
          small: {
            geometry: '120x120>',
            convert_options: '-quality 75 -strip'
          },
          course_thumb: {
            geometry: '395x220^',
            convert_options: '-quality 75 -gravity center -crop \'395x220+0+0\''
          },
          :vitrina => {
            geometry: vitrina_geometry,
            convert_options: vitrina_convert_options
          }
        }
      end
    end
    

提交回复
热议问题