2009-12-09 22 views
10

我正在尋找一種方法來確定圖像方向最好用回形針,但它甚至可能或我需要用戶RMagick或另一個圖像庫爲此?使用回形針進行圖像定位和驗證?

案例情景:當用戶上傳圖片時,我想檢查方向/大小/尺寸以確定圖片是否爲縱向/橫向或正方形,並將此屬性保存到模型中。

回答

11

這是我一般在我的圖像模型中做的。也許它會幫助:

  • 轉換時使用IM的-auto-orient選項。這可確保圖像始終正確旋轉後上傳
  • 我讀處理後的EXIF data並獲得寬度和高度(除其他事項外)
  • 然後你可以只是有基於寬度和高度輸出方向串的實例方法
has_attached_file :attachment, 
    :styles => { 
    :large => "900x600>", 
    :medium => "600x400>", 
    :square => "100x100#", 
    :small => "300x200>" }, 
    :convert_options => { :all => '-auto-orient' }, 
    :storage => :s3, 
    :s3_credentials => "#{RAILS_ROOT}/config/s3.yml", 
    :s3_permissions => 'public-read', 
    :s3_protocol => 'https', 
    :path => "images/:id_partition/:basename_:style.:extension" 

after_attachment_post_process :post_process_photo 

def post_process_photo 
    imgfile = EXIFR::JPEG.new(attachment.queued_for_write[:original].path) 
    return unless imgfile 

    self.width   = imgfile.width    
    self.height  = imgfile.height    
    self.model   = imgfile.model    
    self.date_time  = imgfile.date_time   
    self.exposure_time = imgfile.exposure_time.to_s 
    self.f_number  = imgfile.f_number.to_f  
    self.focal_length = imgfile.focal_length.to_s 
    self.description = imgfile.image_description 
end 
+1

不是稱爲'after_post_process'的回調嗎? – 2012-03-12 14:11:12

+0

這裏是'after_attachment_post_process',因爲Paperclip允許你爲模型中的每個附件聲明後置處理器。你可以通過聲明'after_ATTACHMENT-NAME_post_process'來完成。所以如果他的附件被稱爲「媒體」,他的後處理器將是'after_media_post_process'。 – Joseph 2014-04-09 14:36:21

+0

您可能希望使用'source_file_options:{all:'-auto-orient'}'而不是'convert_options:',因爲它在生成各種樣式之前定位,並且會在樣式中生成預期的圖像大小。 – 2015-01-06 20:41:57

1

當我使用相機拍攝照片時,無論照片是橫向還是縱向,圖像的尺寸都是相同的。不過,我的相機足夠聰明,可以爲我旋轉圖像!太體貼了!這項工作的方式是使用被稱爲exif data的東西,它是由相機放置在圖像上的元數據。它包括的東西,如:相機的類型,當照片拍攝,方向等等

用回形針可以設置回調,特別是你想做的事就是有一個before_post_process回調通過使用庫(您可以在這裏找到一個列表:http://blog.simplificator.com/2008/01/14/ruby-and-exif-data/)讀取exif數據,然後將圖像順時針或逆時針旋轉90度來檢查圖像的方向(您不知道它們在拍攝時如何旋轉相機照片)。

我希望這有助於!

+0

我看着這一點,這也是一個很好的解決方案,雖然本次的圖像上傳的用戶,我真的不相信他們能正確上傳圖片的能力。 – 2009-12-09 17:02:55

5

謝謝你的答案jonnii。

雖然我確實在PaperClip :: Geometry模塊中找到了我要找的東西。

這工作發現:

class Image < ActiveRecord::Base 
    after_save :set_orientation 

    has_attached_file :data, :styles => { :large => "685x", :thumb => "100x100#" } 
    validates_attachment_content_type :data, :content_type => ['image/jpeg', 'image/pjpeg'], :message => "has to be in jpeg format" 

    private 
    def set_orientation 
    self.orientation = Paperclip::Geometry.from_file(self.data.to_file).horizontal? ? 'horizontal' : 'vertical' 
    end 
end 

這當然使得垂直和方形的圖像具有垂直屬性,但是這就是我想要的呢。