Any Paperclip wizards out there know if you can when using Paperclip to save an image, also save the image dimensions (width and height) in 2 extra fields? How do you get such data during the Paperclip upload process?
Just for the sake of completeness, even though previous answers already show good enough suggestions.
You can utilize Paperclip event handlers instead of Rails callbacks. In this case, size will be recalculated only when image changes. (If you're using S3 for storage, this can save quite some time)
has_attached_file :image, :styles => ... after_post_process :save_image_dimensions def save_image_dimensions geo = Paperclip::Geometry.from_file(image.queued_for_write[:original]) self.image_width = geo.width self.image_height = geo.height end
Image don't even have to be downloaded from S3 (or read from a file), paperclip provides it to event handler itself.
See Events section of the readme for details.
When a user uploads an image with paperclip I process it with the following model:
class Picture < ActiveRecord::Base has_attached_file :pic, :styles => { :small => "100x100>" }, :whiny => true after_save :save_geometry def save_geometry unless @geometry_saved self.original_geometry = get_geometry(:original) self.small_geometry = get_geometry(:small) @geometry_saved = true self.save end end def get_geometry(style = :original) begin Paperclip::Geometry.from_file(pic.path(style)).to_s end end end
The get_geometry
function calls ImageMagick identify
to find the geometry of your original and resized images.
I cache the results in a database field. For example if I uploaded an image that was 1024x768
my cached fields would contain:
original_geometry = "1024x768" small_geometry = "100x75"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With