我正在寻找一种方法来确定图像的方向,最好使用Paperclip,但这是否可能,还是我需要使用RMagick或其他图像库?
案例场景:当用户上传图像时,我想检查方向/大小/尺寸,以确定图像是纵向/横向还是正方形,并将此属性保存到模型中。
我正在寻找一种方法来确定图像的方向,最好使用Paperclip,但这是否可能,还是我需要使用RMagick或其他图像库?
案例场景:当用户上传图像时,我想检查方向/大小/尺寸,以确定图像是纵向/横向还是正方形,并将此属性保存到模型中。
这是我在图像模型中通常会做的事情,或许有所帮助:
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
感谢 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
这当然使得竖直和正方形的图片都具有垂直属性,但这正是我想要的。
before_post_process
上设置一个回调函数,通过使用库(您可以在此处找到列表:http://blog.simplificator.com/2008/01/14/ruby-and-exif-data/)读取exif数据来检查图像的方向,然后将图像顺时针或逆时针旋转90度(您不会知道他们拍照时相机旋转的方向)。
after_post_process
吗? - Jakub Hamplafter_attachment_post_process
是因为Paperclip允许您在模型中为每个附件声明后处理器。您可以通过声明after_ATTACHMENT-NAME_post_process
来实现。因此,如果他的附件名为media
,那么他的后处理器将是after_media_post_process
。 - Josephsource_file_options: { all: '-auto-orient' }
而不是convert_options:
,因为它在生成各种样式之前会进行方向校正,并且将产生所需的图像尺寸。 - Joshua Pinter