如何在 Rails 中的载波 gem 中将上传的图像调整为特定宽度

How to resize the uploaded image to specific width in carrierwave gem in Rails

我正在使用 carrierwave 将图像上传到我的 rails 应用程序。

我希望 max-width 固定为特定大小,height 根据 width

当我这样做的时候

version :medium do
   resize_to_limit(600,0)
end

那么图片就出不来了

还有,resize_to_limitresize_to_fit

有什么区别

请指导。

如果您满足于只有一个版本,那么您可以将其添加到您的上传器中:

include CarrierWave::MiniMagick
process resize_to_fill: [600, 0]

这里是 documentation for resize_to_limit:

Resize the image to fit within the specified dimensions while retaining the original aspect ratio. Will only resize the image if it is larger than the specified dimensions. The resulting image may be shorter or narrower than specified in the smaller dimension but will not be larger than the specified values.

这是给 resize_to_fit 的:

Resize the image to fit within the specified dimensions while retaining the original aspect ratio. The image may be shorter or narrower than specified in the smaller dimension but will not be larger than the specified values.

这里是 resize_to_fill:

Resize the image to fit within the specified dimensions while retaining the aspect ratio of the original image. If necessary, crop the image in the larger dimension.

您需要重新创建新版本的图片上传器,例如:-

version :medium do
    process :resize_to_fill => [600,0]
end

然后重新创建它们:-

User.all.each do |user|
    user.avatar.recreate_versions!
end