Skip to content

How to: Get version image dimensions

Henrik Nyh edited this page Jul 29, 2014 · 16 revisions

ImageMagick can tell you the dimensions of an image.

If you assign the dimensions to the model (that you've mounted the uploader to) in a custom processor, that will be saved along with the image path when you upload.

Shelling out manually

class ImageUploader < CarrierWave::Uploader::Base 
  process :store_dimensions

  # If you like, you can call this inside a version like this
  # instead of at the top level.
  # That will store the dimensions for this version.
  version :show do
    process :resize_to_limit => [500, 500]
    process :store_dimensions
  end

  private

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

RMagick

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_dimensions

  private

  def store_dimensions
    if file && model
      img = ::Magick::Image::read(file.file).first
      model.width = img.columns
      model.height = img.rows
    end
  end
end

MiniMagick

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

  process :store_dimensions

  private

  def store_dimensions
    if file && model
      model.width, model.height = ::MiniMagick::Image.open(file.file)[:dimensions]
    end
  end
end
Clone this wiki locally