10

我正在寻找一种最好使用 Paperclip 确定图像方向的方法,但它甚至可能还是我需要为此使用 RMagick 或其他图像库?

案例场景:当用户上传图像时,我想检查方向/大小/尺寸以确定图像是纵向/横向还是方形,并将此属性保存到模型中。

4

3 回答 3

12

这是我通常在图像模型中所做的。也许它会有所帮助:

  • 我在转换时使用 IM 的 -auto-orient 选项。这可确保上传后图像始终正确旋转
  • 我在处理后读取EXIF 数据并获取宽度和高度(除其他外)
  • 然后,您可以只使用一个实例方法,该方法根据宽度和高度输出方向字符串
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
于 2009-12-10T19:59:01.193 回答
5

感谢乔尼的回答。

虽然我确实在 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

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

于 2009-12-09T16:46:40.053 回答
1

当我用相机拍照时,无论照片是横向还是纵向,图像的尺寸都是相同的。但是,我的相机足够聪明,可以为我旋转图像!考虑周全!这项工作的方式是使用一种叫做exif data元数据的东西,它是相机放置在图像上的元数据。它包括以下内容:相机的类型,拍摄照片的时间,方向等......

使用回形针,您可以设置回调,特别是您想要做的是before_post_process通过使用库读取 exif 数据来检查图像方向的回调(您可以在此处找到列表:http://blog. simplificator.com/2008/01/14/ruby-and-exif-data/),然后将图像顺时针或逆时针旋转 90 度(您不会知道他们在拍照时以哪种方式旋转相机)。

我希望这有帮助!

于 2009-12-09T16:25:30.910 回答