【问题标题】:Carrierwave: Scale image if the size is larger than (conditionally create versions)Carrierwave:如果尺寸大于则缩放图像(有条件地创建版本)
【发布时间】:2012-09-12 15:18:55
【问题描述】:

只有当图像大于版本的大小时,才可以使用carrierwave 创建一个版本(例如拇指)??

例子:

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

【问题讨论】:

    标签: ruby-on-rails-3 carrierwave minimagick


    【解决方案1】:

    我试过了,但对我不起作用。 在开发中调整为大图像时,服务器被阻止。

    • 载波 (0.9.0)
    • rmagick (2.13.2)

    所以我看了一下文档:http://carrierwave.rubyforge.org/rdoc/classes/CarrierWave/RMagick.html

    有一个奇妙的功能:resize_to_limit(width, height)

    调整图像大小以适应指定尺寸,同时保持原始纵横比。仅当图像大于指定尺寸时才会调整图像大小。生成的图像可能比在较小尺寸中指定的更短或更窄,但不会大于指定值。

    我的代码如下所示:

    version :version_name, from_version: :parent_version_name do
        process resize_to_limit: [width, nil]
    end
    

    仅当宽度较大时,它才会调整大小以适应宽度,尊重 w/h 的比率。

    【讨论】:

      【解决方案2】:

      我定义了一种方法,如果图像超过给定的宽度,则将其操作到您的大小,在这种情况下为 32 像素。将此代码放入您的 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
      

      【讨论】:

      • 新语法:img.resize_to_fit!(width, img.rows) if img.columns >= width
      【解决方案3】:

      实际上@Roza 解决方案对我不起作用。 我不得不像这样修改方法:

      process :resize_to_width => [650, nil]
      
      def resize_to_width(width, height)
        manipulate! do |img|
          if img.columns >= width
            img.resize(width)
          end
          img = yield(img) if block_given?
          img
        end
      end
      

      我使用 rmagick (2.13.2) 和 rails 3.2.13,carrierwave (0.8.0)

      【讨论】:

        猜你喜欢
        • 2015-10-24
        • 2018-07-17
        • 2023-02-04
        • 1970-01-01
        • 2018-06-16
        • 2013-03-04
        • 1970-01-01
        • 1970-01-01
        • 2010-10-15
        相关资源
        最近更新 更多