Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Carrierwave image dimension

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.

like image 795
King Pangilinan Avatar asked Jan 13 '12 23:01

King Pangilinan


3 Answers

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
like image 195
DASGiB Avatar answered Nov 16 '22 22:11

DASGiB


You can save the height and width as attributes with your model quite easily if using Rmagick. In the Carrierwave uploader:

class ArtworkUploader < CarrierWave::Uploader::Base

  def geometry
    @geometry ||= get_geometry
  end

  def get_geometry
    if @file
      img = ::Magick::Image::read(@file.file).first
      geometry = { width: img.columns, height: img.rows }
    end
  end

end

And in your model:

class Artwork < ActiveRecord::Base

  mount_uploader :image, ArtworkUploader

  before_save :save_image_dimensions

  private

    def save_image_dimensions
      if image_changed?
        self.image_width  = image.geometry[:width]
        self.image_height = image.geometry[:height]
      end
    end
end
like image 12
JamieD Avatar answered Nov 16 '22 21:11

JamieD


Or just use FastImage. This makes it much easier to measure attachments retroactively.

like image 2
Micah Alcorn Avatar answered Nov 16 '22 22:11

Micah Alcorn