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.
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
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
Or just use FastImage. This makes it much easier to measure attachments retroactively.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With