Skip to content

How to: Get version image dimensions

Henrik Nyh edited this page Jul 29, 2014 · 16 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

Or with MiniMagick:

class ImageUploader < CarrierWave::Uploader::Base
  include CarrierWave::MiniMagick

  process :store_dimensions

  private

  def store_dimensions
    return unless @file

    width, height = ::MiniMagick::Image.open(@file.file)[:dimensions]

    if model
      model.width = width
      model.height = height
    end
  end
end

Clone this wiki locally