Carrierwave image dimension

King Pangilinan picture King Pangilinan · Jan 14, 2012 · Viewed 7.9k times · Source

How can I get the width and height of the current instance of carrierwave?

Something like this:

car_images.each do | image|
  image_tag( image.photo_url, :width => image.photo_width, :height => image.photo_height)
end

Unfortunately image.photo_width and image.photo_height are not working. I need to specify the width and height of the images, it is required on the jquery plugin I'm using.

Answer

DASGiB picture DASGiB · Feb 4, 2012

Combine https://github.com/jnicklas/carrierwave/wiki/How-to:-Get-version-image-dimensions and https://github.com/jnicklas/carrierwave/wiki/How-to:-Store-the-uploaded-file-size-and-content-type and you get:

class Image
  before_save :update_image_attributes

  private

  def update_image_attributes
    if image.present?
      self.content_type = image.file.content_type
      self.file_size = image.file.size
      self.width, self.height = `identify -format "%wx%h" #{image.file.path}`.split(/x/)
      # if you also need to store the original filename:
      # self.original_filename = image.file.filename
    end
  end
end