Skip to content

How to: Get version image dimensions

bjnord edited this page Feb 10, 2012 · 9 revisions

Simple trick to get the image dimensions generated by some version:

class LogoUploader < CarrierWave::Uploader::Base 
  # ... 
  version :show do
    # do the processing you need
    process :resize_to_limit => [500, 500]
    # and, here comes the trick, use some processor to access the file generated
    process :get_version_dimensions 
  end

  def get_version_dimensions
    width, height = `identify -format "%wx%h" #{file.path}`.split(/x/) 
  end
  # ...
end

If you have enabled RMagick, there's a more direct way to obtain the dimensions (without using the external "identify" program), as well as storing them in your model. As found on this page via Stack Overflow:

class ImageUploader < CarrierWave::Uploader::Base
  include CarrierWave::RMagick
  # ...
  process :store_geometry
  def store_geometry
    if @file
      img = ::Magick::Image::read(@file.file).first
      if model
        model.width = img.columns
        model.height = img.rows
      end
    end
  end
  # ...
end
Clone this wiki locally