Carrierwave – 将图像调整为固定宽度
我正在使用RMagick并希望将我的图像调整为100px的固定宽度,并按比例缩放高度。 例如,如果用户要上传300x900px,我希望将其缩放到100x300px。
把它放在你的上传器文件中:
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
请记住,如果图像小于100像素, resize_to_fit
会放大图像。 如果您不希望它这样做,请将其替换为resize_to_limit
。
我用
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.
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的固定宽度
实际上不是更好的解决方案:
process :resize_to_fit => [100, -1]
这样您就不必限制高度了
编辑:刚刚意识到这只适用于MiniMagick,对于RMagick你似乎没有选择,只能在高度上添加一个大号