Search code examples
ruby-on-railscarrierwaveminimagick

CarrierWave - Set width and max height of images


I use CarrierWave and I want to resize the images to a width of 220px and a max-height of 220px. If I use process :resize_to_fit => [220,220] it could be that the width is not 220px. What can I do?


Solution

  • An improvment of Andy H's answer:

    process :resize => [220, 220]
    
    protected
    
    def resize(width, height, gravity = 'Center')
      manipulate! do |img|
        img.combine_options do |cmd|
          cmd.resize "#{width}"
          if img[:width] < img[:height]
            cmd.gravity gravity
            cmd.background "rgba(255,255,255,0.0)"
            cmd.extent "#{width}x#{height}"
          end
        end
        img = yield(img) if block_given?
        img
      end
    end