使用Paperclip进行图片方向和验证?

10

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

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

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

1
回调函数不是叫做after_post_process吗? - Jakub Hampl
这里使用after_attachment_post_process是因为Paperclip允许您在模型中为每个附件声明后处理器。您可以通过声明after_ATTACHMENT-NAME_post_process来实现。因此,如果他的附件名为media,那么他的后处理器将是after_media_post_process - Joseph
1
你可能想使用 source_file_options: { all: '-auto-orient' } 而不是 convert_options:,因为它在生成各种样式之前会进行方向校正,并且将产生所需的图像尺寸。 - Joshua Pinter

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

这当然使得竖直和正方形的图片都具有垂直属性,但这正是我想要的。


1
当我使用相机拍照时,无论照片是横向还是纵向,图像的尺寸都是相同的。然而,我的相机足够智能,可以为我旋转图像!这真是太贴心了!它的工作原理是使用一种称为“exif数据”的东西,它是由相机放置在图像上的元数据。它包括诸如:相机类型、拍摄时间、方向等信息...
使用Paperclip,您可以设置回调函数,具体来说,您需要在before_post_process上设置一个回调函数,通过使用库(您可以在此处找到列表:http://blog.simplificator.com/2008/01/14/ruby-and-exif-data/)读取exif数据来检查图像的方向,然后将图像顺时针或逆时针旋转90度(您不会知道他们拍照时相机旋转的方向)。
希望这可以帮助您!

我研究了一下,这也是一个很好的解决方案,但这次图像上传是由用户完成的,我不太相信他们能正确地上传图片。 - Antony Sastre

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接