-
Notifications
You must be signed in to change notification settings - Fork 1.7k
How to: Get image dimensions
Henrik Nyh edited this page Jul 29, 2014
·
5 revisions
ImageMagick can tell you the dimensions (geometry/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.
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
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
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