Getting width and height of image in model in the Ruby Paperclip GEM

前端 未结 2 1916
半阙折子戏
半阙折子戏 2020-12-24 00:39

Trying to get the width and height of the uploaded image while still in the model on the initial save.

Any way to do this?

Here\'s the snippet of code I\'ve

2条回答
  •  盖世英雄少女心
    2020-12-24 01:05

    Ahh, figured it out. I just needed to make a proc.

    Here's the code from my model:

    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
    

提交回复
热议问题