Ruby-on-rails Carrierwave - 将图像调整为固定宽度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8570181/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Carrierwave - Resizing images to fixed width
提问by David
I'm using RMagick and want my images to be resized to a fixed width of 100px, and scale the height proportionally. For example, if a user were to upload a 300x900px, I would like it to be scaled to 100x300px.
我正在使用 RMagick 并希望将我的图像调整为 100 像素的固定宽度,并按比例缩放高度。例如,如果用户要上传 300x900 像素,我希望将其缩放为 100x300 像素。
回答by iwasrobbed
Just put this in your uploader file:
只需将其放入您的上传器文件中:
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
Documentation and example here: http://www.imagemagick.org/RMagick/doc/image3.html#resize_to_fit
此处的文档和示例:http: //www.imagemagick.org/RMagick/doc/image3.html#resize_to_fit
Keep in mind, resize_to_fitwill scale up images if they are smaller than 100px. If you don't want it to do that, then replace that with resize_to_limit.
请记住,resize_to_fit如果图像小于 100 像素,则会放大图像。如果您不希望它这样做,请将其替换为resize_to_limit.
回答by Giang Nguyen
I use
我用
process :resize_to_fit => [100, 10000]
Use 10000or any very big number to let Carrierwave know the height is free, just resize to the width.
使用10000或任何非常大的数字让 Carrierwave 知道高度是免费的,只需调整宽度即可。
@iWasRobbed: I don't think that's the correct solution. According to the link you pasted about resize_to_fit: The maximum height of the resized image. If omitted it defaults to the value of new_width.So in your case process :resize_to_fit => [100, nil]is equivalent to process :resize_to_fit => [100, 100]which doesn't guarantee that you will always get the fixed width of 100px
@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 的固定宽度
回答by Rafael Vidaurre
Wouldn't a better solution actually be:
更好的解决方案实际上不是:
process :resize_to_fit => [100, -1]
This way you don't have to limit height at all
这样你就不必限制高度了
EDIT: Just realized this only works with MiniMagick, For RMagick you seem to have no option but to add a large number to the height
编辑:刚刚意识到这只适用于 MiniMagick,对于 RMagick,您似乎别无选择,只能在高度上添加一个大数字

