Carrierwave - 将图像调整为固定宽度

Dav*_*vid 27 ruby ruby-on-rails rmagick carrierwave

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

iwa*_*bed 47

把它放在你的上传器文件中:

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
Run Code Online (Sandbox Code Playgroud)

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

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


Gia*_*yen 16

我用

process :resize_to_fit => [100, 10000]
Run Code Online (Sandbox Code Playgroud)

使用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 => [100, nil]相当于process :resize_to_fit => [100, 100]不保证您将始终获得100px的固定宽度


Raf*_*rre 12

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

process :resize_to_fit => [100, -1]
Run Code Online (Sandbox Code Playgroud)

这样您就不必限制高度了

编辑:刚刚意识到这只适用于MiniMagick,对于RMagick你似乎别无选择,只能在高处添加一个大号