Retrieving Image Height with Carrierwave

Ruby on Rails - Carrierwave get the image dimension width and height

You have to install ImageMagick, RMagick or MiniMagick. Then you open the file (image) before you can find out its height.

Example: https://github.com/jnicklas/carrierwave#conditional-versions (see the is_landscape? method), copied here:

  def is_landscape? picture
image = MiniMagick::Image.open(picture.path)
image[:width] > image[:height]
end

Or this other related question:

Carrierwave and mini_magick finding widths & height

Retrieving image height with CarrierWave

You can adjust and use the method described here: http://code.dblock.org/carrierwave-saving-best-image-geometry

It adds a process then call Magick's method to fetch image geometry.

Code:

  version :post do
process :resize_to_fit => [200, nil]
process :get_geometry

def geometry
@geometry
end
end

def get_geometry
if (@file)
img = ::Magick::Image::read(@file.file).first
@geometry = [ img.columns, img.rows ]
end
end

Carrierwave getting image width and height and storing it in an hstore field

Try this

class FileUploader < CarrierWave::Uploader::Base

# Include RMagick or MiniMagick support:
include CarrierWave::RMagick
process :store_geometry, :if => :image?

#......
#......
#......

def store_geometry
if image?(@file)
img = ::Magick::Image::read(@file.file).first
if model
model.ImageWidth = img.columns
model.ImageHeight = img.rows
end
end
end
end

#Hstore

  %w[ImageHeight ImageWidth].each do |key|
attr_accessible key

define_method(key) do
properties && properties[key]
end

define_method("#{key}=") do |value|
self.properties = (properties || {}).merge(key => value)
end
end

Assumptions

I'm assuming there's a reason you have the image method that checks if the file is an image, that must mean you're uploading other file formats as well. Well, i've put it to good use here, it calls process_geometry method only if the file is an image.
Hope it helps.

Sending information from image uploader to the model carrierwave

To use some fields only for validations, one can define attr_accessor on the model, but need to keep in mind that these attributes would only be available when assigned explicitly(since not backed by DB columns).

For current scenario, you can keep your current code and define attr_accessor :height, :width on the model and use them in validations.



Related Topics



Leave a reply



Submit