在教程使用的carrierwave圖片管理工具能夠讓我們上傳一張圖片獲得不同尺寸的圖片
class MyUploader < CarrierWave::Uploader::Base
include CarrierWave::MiniMagick
process resize_to_fit: [800, 800]
version :thumb do
process resize_to_fill: [200,200]
end
version :medium do
process resize_to_fill: [400,400]
end
end
但是同樣的寬高比得出的都是四四方方的圖片,如果要將圖片設(shè)置成矩形該怎么辦呢沐序?比如:
在首頁(yè)我要的是這個(gè)比例
在index頁(yè)面我要的是這個(gè)比例:
而在show頁(yè)面則是這樣:
那該怎么做呢跃赚? 可能首先想到的是去把thumb和medium中的尺寸改成自己想要的惧眠,但是刷新頁(yè)面發(fā)現(xiàn)什么都沒有改變疹瘦,還是老樣子霜定,為什么呢嗤放?
我們來看看官方的解釋
When this uploader is used, an uploaded image would be scaled to be no larger than 800 by 800 pixels. A version called thumb is then created, which is scaled and cropped to exactly 200 by 200 pixels.
One important thing to remember is that process is called before versions are created. This can cut down on processing cost.
意思是當(dāng)使Uploader時(shí)思喊,首先就是運(yùn)行這一行process resize_to_fit: [800, 800]
,將圖片裁剪成一個(gè)固定尺寸;接著才會(huì)根據(jù)[800,800]的比例生成thumb和medium尺寸的圖片次酌。
這樣看來恨课,如果你已經(jīng)建立了一個(gè)產(chǎn)品,那么當(dāng)前圖片的thumb和medium尺寸的圖片已經(jīng)生成了岳服,臨時(shí)更改的尺寸只能在下一個(gè)新建產(chǎn)品中才能有效剂公。
注意: 在設(shè)置resize_to_fit: [width,height]的時(shí)候,如果只想固定某一個(gè)值吊宋,比如讓寬度固定在1000纲辽,高度不設(shè)限,那么就可以用一個(gè)極大值代替高度贫母,例如: [100,10000]
同樣文兑,version版本數(shù)量是完全可以自定義的,只需要在image_tag中使用相對(duì)應(yīng)的URL即可腺劣,例如:定義了一個(gè)
version :small do
process resize_to_fill: [200, 100]
end
那么只需使用<%= image_tag(event.image.small.url) %>
即可绿贞。