Search code examples
ruby-on-rails-3carrierwaveminimagick

Carrierwave: Scale image if the size is larger than (conditionally create versions)


Is possible with carrierwave create a version (for example thumb) only if the image is larger than the size of the version??

Example:

version :thumb, :if => :is_thumbnable? do 
    process :resize_to_fit => [32,nil]
end

protected

def is_thumbnable?(file)
  image ||= MiniMagick::Image.open(file.path)
  if image.nil?
    if image['width'] >= 32 || image['height'] >= 32
      true
    else
      false
    end
  else
    false
  end
end

Solution

  • I defined method in which if image exceed given width then manipulate it to your size the 32 pixels in this case. Put this code in your ImageUploader:

      version :thumb do 
        process :resize_to_width => [32, nil]
      end
    
      def resize_to_width(width, height)
        manipulate! do |img|
          if img[:width] >= width
            img.resize "#{width}x#{img[:height]}"
          end
          img = yield(img) if block_given?
          img
        end
      end