2013-01-06 2 views
0

CarrierWave는 ActiveRecord를 사용하여 이미지를 업로드 할 때 이미지의 크기를 조정하는 작업을하고 있습니다. 그러나 처리중인 ActiveRecord 모델에서 이미지가 가로 또는 세로인지 여부를 기록 할 수 있습니까?CarrierWave 모델을 업데이트 하시겠습니까?

답변

1

README에서, 당신은 사진의 방향을 확인하려면 다음 사용할 수 있습니다

def landscape?(picture) 
    image = MiniMagick::Image.open(picture.path) 
    image[:width] > image[:height] 
end 

당신은이를 사용할 수를 귀하의 모델에 before_save (예 : CarrierWave 위키에있는 this example)을 약간 수정했습니다 :

class Asset < ActiveRecord::Base 
    mount_uploader :asset, AssetUploader 

    before_save :update_asset_attributes 

    private 

    def update_asset_attributes 
    if asset.present? && asset_changed? 
     self.landscape = landscape?(asset) 
    end 
    end 

    def landscape?(picture) # ... as above ... 
end 

업데이트 : 업 로더에서이를 수행하려면 최선의 방법이 확실하지 않습니다. 하나의 옵션은 사용자 지정 처리 방법을 쓸 수도 :

사실을 이용한다
class AssetUploader < CarrierWave::Uploader::Base 
    include CarrierWave::MiniMagick 

    process :resize => [200, 200] 

    private 

    def resize(width, height) 
    resize_to_limit(width, height) do |image| 
     model.landscape = image[:width] > image[:height] 
     image 
    end 
    end 
end 

그 MiniMagick 방법 yield 추가 처리를위한 화상 이미지를 두 번 로딩 피하도록.

+0

나는이 사진을 찍었습니다. 작동하지만, 이미지를 두 번로드해야합니다. 한 번 크기를 변경하고 한 번 너비와 높이를 찾으십시오. 메모리를 제대로 사용하지 않는 것처럼 보입니다! 모델 내부가 아닌 업 로더 내에서이 정보를 얻을 수 있습니까? –

+1

네, 확실히 가능합니다. 내 대답에 가능한 접근법을 추가했습니다. –

+0

awe- * 더 많은 문자를 써야합니다. * -some –

1

당신은 당신의 업 로더 파일에이 방법을 추가 할 수 있습니다

include CarrierWave::RMagick 

def landscape? picture 
    if @file 
    img = ::Magick::Image::read(@file.file).first 
    img.columns > img.rows 
    end 
end 
관련 문제