使用Paperclip进行图像定位和验证?

Ant*_*tre 10 ruby-on-rails image-processing paperclip

我正在寻找一种方法来确定图像方向,最好使用Paperclip,但它是否可能,或者我是否需要使用RMagick或其他图像库?

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

Cal*_*eed 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
Run Code Online (Sandbox Code Playgroud)


Ant*_*tre 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
Run Code Online (Sandbox Code Playgroud)

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