Skip to content

How to: Get image dimensions

Hyunjoon KIM edited this page Nov 1, 2023 · 5 revisions

ImageMagick can tell you the dimensions (width and height) 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.

Note: This may be obvious for most people reading this, but you will need to set up a field in your model that corresponds with model.width & model.height.

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 use the RMagick library, there's a nicer way to obtain the dimensions. 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

The MiniMagick library also has convenience methods so you don't have to shell out.

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

Vips

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

  process :store_dimensions

  private

  def store_dimensions
    if file && model
      model.width, model.height = ::Vips::Image.new_from_file(file.file).size
    end
  end
end
Clone this wiki locally