ruby-on-railsrubydragonfly-gem

Rails/Dragonfly: how to update magic colums like image_width


I use dragonfly to handle image attachments in my rails app. I use the magic columns image_width and image_height in my model. This worked nicely. Now I have gotten some images with a image_uid in the model, image is accessible, but image_width and image_height are not set. (It happened with the simple_dragonfly_preview plugin) Now how can I force to recalculate the values? So something like this in the model:

before_save :update_image_fields

def update_image_fields
  logger.info "Image size update"
  if image_uid.present?
    self.image_width = image.width # what to call here?
    self.image_height = image.height
   end
 end

Solution

  • You can calculate dimensions of your image using ImageMagic analyzers http://markevans.github.io/dragonfly/imagemagick/#analysers.

    Given you already configured ImageMagick plugin, the code to recalculate your image's height and width looks like this:

    Photo.where(image_width:nil).each do |photo|
      photo.image_width = photo.image.analyse(:width)
      photo.image_height = photo.image.analyse(:height)
      photo.save
    end