2009-12-09 24 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 

这当然使得垂直和方形的图像具有垂直属性,但是这就是我想要的呢。