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

前端 未结 2 1912
半阙折子戏
半阙折子戏 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条回答
  •  梦毁少年i
    2020-12-24 01:05

    class Asset
    
    include Mongoid::Paperclip
    before_save :extract_dimensions
    
    field :width, type: Integer
    field :height, type: Integer
    
    has_mongoid_attached_file :data
    
      def extract_dimensions
        return unless is_image?
    
        tempfile = data.queued_for_write[:original]
        unless tempfile.nil?
          geometry = Paperclip::Geometry.from_file(tempfile)
          self.width = geometry.width.to_i
          self.height = geometry.height.to_i
        end
    
        true # wont save if false 
      end
    
      def is_image?
        data_content_type =~ %r{^(image|(x-)?application)/(bmp|gif|jpeg|jpg|pjpeg|png|x-png)$}
      end
    
    end
    

提交回复
热议问题