【问题标题】:Carrierwave - Resizing images to fixed widthCarrierwave - 将图像大小调整为固定宽度
【发布时间】:2012-01-24 02:32:11
【问题描述】:

我正在使用 RMagick 并希望将我的图像调整为 100 像素的固定宽度,并按比例缩放高度。例如,如果用户要上传 300x900 像素,我希望将其缩放为 100x300 像素。

【问题讨论】:

    标签: ruby-on-rails ruby rmagick carrierwave


    【解决方案1】:

    只需将其放入您的上传文件中即可:

    class ImageUploader < CarrierWave::Uploader::Base
    
      version :resized do
        # returns an image with a maximum width of 100px 
        # while maintaining the aspect ratio
        # 10000 is used to tell CW that the height is free 
        # and so that it will hit the 100 px width first
        process :resize_to_fit => [100, 10000]
      end
    
    end
    

    此处的文档和示例:http://www.imagemagick.org/RMagick/doc/image3.html#resize_to_fit

    请记住,resize_to_fit 会放大小于 100 像素的图像。如果您不希望它这样做,请将其替换为 resize_to_limit

    【讨论】:

    • Giang Nguyen 指出:关于载波和图像处理,[100, nil] 似乎等同于[100, 100]
    【解决方案2】:

    我用

    process :resize_to_fit => [100, 10000]
    

    使用10000 或任何非常大的数字让Carrierwave 知道高度是空闲的,只需调整宽度即可。

    @iWasRobbed:我认为这不是正确的解决方案。根据您粘贴的有关resize_to_fit 的链接:The maximum height of the resized image. If omitted it defaults to the value of new_width. 所以在您的情况下process :resize_to_fit =&gt; [100, nil] 相当于process :resize_to_fit =&gt; [100, 100],这并不能保证您将始终获得100px 的固定宽度

    【讨论】:

      【解决方案3】:

      实际上不是更好的解决方案:

      process :resize_to_fit => [100, -1]
      

      这样你就完全不用限制高度了

      编辑:刚刚意识到这仅适用于 MiniMagick,对于 RMagick,您似乎别无选择,只能在高度上添加一个大数字

      【讨论】:

      • 请注意[-1, 100] 不起作用,这意味着您无法创建固定高度的图像缩略图。
      猜你喜欢
      • 2015-05-19
      • 2012-08-14
      • 2014-08-17
      • 2013-11-03
      • 2013-08-12
      • 2014-01-16
      • 2012-01-03
      • 2012-11-20
      相关资源
      最近更新 更多