在Ruby Paperclip GEM中获取模型中图像的宽度和高度

Cor*_*rey 16 ruby-on-rails paperclip

尝试在初始保存时仍然在模型中获取上载图像的宽度和高度.

有什么办法吗?

这是我从模型中测试过的代码片段.当然它在"instance.photo_width"上失败了.

has_attached_file :photo,
                      :styles => {
                      :original  => "634x471>",
                      :thumb => Proc.new { |instance|                       
                                  ratio = instance.photo_width/instance.photo_height
                                  min_width   = 142
                                  min_height  = 119
                                  if ratio > 1
                                    final_height  = min_height
                                    final_width   = final_height * ratio
                                  else
                                    final_width   = min_width
                                    final_height  = final_width * ratio
                                  end
                                  "#{final_width}x#{final_height}" 
                                }
                    }, 
                    :storage => :s3,
                    :s3_credentials => "#{RAILS_ROOT}/config/s3.yml",
                    :path => ":attachment/:id/:style.:extension",
                    :bucket => 'foo_bucket' 
Run Code Online (Sandbox Code Playgroud)

因此,我基本上是尝试这样做,以根据初始图像尺寸获得自定义缩略图的宽度和高度.

有任何想法吗?

Cor*_*rey 25

啊,想通了.我只需要做一个过程.

这是我的模型中的代码:

class Submission < ActiveRecord::Base

  #### Start Paperclip ####

  has_attached_file :photo, 
                    :styles => {
                      :original  => "634x471>",
                      :thumb => Proc.new { |instance| instance.resize }
                    }, 
                    :storage => :s3,
                    :s3_credentials => "#{RAILS_ROOT}/config/s3.yml",
                    :path => ":attachment/:id/:style.:extension",
                    :bucket => 'foo_bucket' 

  #### End Paperclip ####

  def resize     
     geo = Paperclip::Geometry.from_file(photo.to_file(:original))

     ratio = geo.width/geo.height  

     min_width  = 142
     min_height = 119

     if ratio > 1
       # Horizontal Image
       final_height = min_height
       final_width  = final_height * ratio
       "#{final_width.round}x#{final_height.round}!"
     else
       # Vertical Image
       final_width  = min_width
       final_height = final_width * ratio
       "#{final_height.round}x#{final_width.round}!"
     end
  end  
end
Run Code Online (Sandbox Code Playgroud)

  • 从Paperclip 3.x开始,不再支持`photo.to_file`.你可以改用`geo = Paperclip :: Geometry.from_file(Paperclip.io_adapters.for(photo))` (7认同)