Reputation: 5594
CarrierWave is doing an awesome job with ActiveRecord of resizing my images as I upload them - but I'd like to be able to record whether the image is landscape or portrait in my ActiveRecord model as it's being processed - is this possible?
Upvotes: 0
Views: 614
Reputation: 6644
From the README, you can use the following to determine the orientation of the picture:
def landscape?(picture)
image = MiniMagick::Image.open(picture.path)
image[:width] > image[:height]
end
You could use this in a before_save
on your model, like in this example from the CarrierWave wiki, which I've adapted slightly:
class Asset < ActiveRecord::Base
mount_uploader :asset, AssetUploader
before_save :update_asset_attributes
private
def update_asset_attributes
if asset.present? && asset_changed?
self.landscape = landscape?(asset)
end
end
def landscape?(picture) # ... as above ...
end
Update: To do it in the uploader, I'm not sure of the best approach. One option might be to write a custom processing method:
class AssetUploader < CarrierWave::Uploader::Base
include CarrierWave::MiniMagick
process :resize => [200, 200]
private
def resize(width, height)
resize_to_limit(width, height) do |image|
model.landscape = image[:width] > image[:height]
image
end
end
end
which takes advantage of the fact that the MiniMagick methods yield
the image for further processing, so as to avoid loading the image a second time.
Upvotes: 1
Reputation: 736
you can add this method to your uploader file:
include CarrierWave::RMagick
def landscape? picture
if @file
img = ::Magick::Image::read(@file.file).first
img.columns > img.rows
end
end
Upvotes: 1