You can access the dimensions either before uploading to Cloudinary or afterwards.
For accessing image dimensions after uploading, you can add to your model entity the following code for processing metadata returned by Cloudinary. Please make sure after_save is placed after the mount_uploader definition.
after_save :update_dimensions def update_dimensions if self.picture.present? && self.picture.metadata.present? width = self.picture.metadata["width"] height = self.picture.metadata["height"] # TODO: Update model entity end end
If you need to perform calculations on your side before uploading, you can use a code like the following one in your uploader class:
class ImageUploader < CarrierWave::Uploader::Base include Cloudinary::CarrierWave process :set_width_height def set_width_height img = ::MiniMagick::Image::read(File.binread(@file.file)) width = img[:width] height = img[:height] # TODO: Perform your calculations instead of assignments new_width = width new_height = height return { :crop=>:fill, :width => new_width, :height=>new_height } end end
Comments
4 comments
doesn't work.
NoMethodError: undefined method `[]' for nil:NilClass
Hi Nicholas,
We'll need some more information about this.
You're more than welcomed to open a ticket and share your code with us, so we'll be able to further assist with this issue.
Hello,
i would love to be able to use this solution,
but none of the two code examples work for us in our Rails 3.2 project.
could i ask for any help?
i am happy to share code, too
Here's a basic sample project demonstrating this (on Rails 4):
https://github.com/taragano/Rails_retrieve_image_data
Please sign in to leave a comment.