Carrierwave and mini_magick finding widths & height

后端 未结 4 1025
慢半拍i
慢半拍i 2021-02-06 12:30

After a bit of investigation I decided to use Carrierwave and mini_magick on my new rail3 app.

I\'ve set it up and it works perfectly. However I have a one question. I\

4条回答
  •  囚心锁ツ
    2021-02-06 12:35

    I think the best way is to store the image dimensions in the model (database).

    In my case, the model name is attachment. Then I created a migration:

    rails g migration add_dimensions_to_attachments image_width:integer image_height:integer
    

    After that, run the migration:

    rake db:migrate
    

    In my Image Uploader file app/uploaders/image_uploader.rb, I have:

    class ImageUploader < CarrierWave::Uploader::Base
    
        include CarrierWave::MiniMagick
    
        process :store_dimensions
    
        private
    
        def store_dimensions
          if file && model
            model.image_width, model.image_height = ::MiniMagick::Image.open(file.file)[:dimensions]
          end
        end
      end
    

    With this, the image dimensions is saved in the upload step.

    To get the dimensions, I simply run attachment.image_width or attachment.image_height

    See the reference here.

提交回复
热议问题