Using Paperclip to save the width and height of the attachemnt

When using Paperclip to save an attached image, how do I get & store the dimensions of the image? Best way is to create two fields to store the width & height and then just populate those fields when the image loads. (Other solutions, like reading it dynamically each, incur a lot of unnecessary disk activity.) Be sure to checkout some basic tutorials on Paperclip if you are unfamiliar with it generally. (see references below 1 2 3)

Step by step instructions.

1. create a new file at lib/paperclip_processors/thumbnail_with_dimensions.rb

2. Paste the contents of this gist into the newly created file:

3. Make a width and height columns on your object (script/generate migration AddWidthHeighToSomething)

def self.up
  add_column :yourtablename, :width, :integer
  add_column :yourtablename, :height, :integer

 def self.down
  remove_column :yourtablename, :width
  remove_column :yourtablename, :height

4. On your model, you’ll want to define your has_attached_file this way (I left out the options for :path and :url which are at the same hiearchy as :styles). Note that you have to pass :mystyle back to the preprocessor, same name as the name of the style itself. This seems counter-intuitive, but it is a needed hack because of how closures work. Just make sure you put :mystyle => and then the symbol that you used above that hash to declare the name of the style -- use the very same symbol name. (In the example below, this is :normal -- notice that it is used to declare the name of the style and then also passed to the :mystyle option)

has_attached_file :resource,
   :styles => {
     :normal =>
      :geometry => “”,
      :processors => [:thumbnail_with_dimensions],
      :mystyle => :normal
     :small => “100×100>”,
     :thumbnail => “60×60>” 

5. On your model:

 before_save :set_dimensions, :if =>{|obj| obj.width.nil? || obj.height.nil? }

 def set_dimensions
  self.width = resource.width
  self.height = resource.height

1. Jim Neath
2. Railscast
3. Paperclip home

Leave a Reply

Your email address will not be published. Required fields are marked *

Previous post NY Tech Meetup August 3rd, 2010
Next post The Magical Attribute Reader