2

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
Meier
  • 3,858
  • 1
  • 17
  • 46

1 Answers1

1

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
dimakura
  • 7,575
  • 17
  • 36
  • it looks like the `image.width` call just uses the magic column, I keep getting empty dimensions. – Meier Sep 22 '15 at 16:49
  • According to https://github.com/markevans/dragonfly/blob/master/lib/dragonfly/image_magick/analysers/image_properties.rb#L9 it should invoke Imagemagick's `identify` command to get width and height – dimakura Sep 22 '15 at 16:53
  • When I debug, it calls "ensure_uses_cached_magic_attributes", which of course finds that I have magic attributs defined. – Meier Sep 22 '15 at 17:04
  • @Meier see my updated answer. You should use `photo.image.analyse(:width)` – dimakura Sep 22 '15 at 17:23