Unfortunately, CarrierWave does not support storing image data (such as width and height) out of the box
There are various solutions online, such as this (StackOverflow), that seem to work at first, but they break on form re-submit (e.g. when validations fail)
Another solution is posted in CarrierWave's Google group that gets much closer to a working solution:
before :cache, :capture_size_before_cache
before :retrieve_from_cache, :capture_size_after_retrieve_from_cache
def capture_size_before_cache(new_file)
model.header_width, model.header_height = `identify -format "%wx%h" #{new_file.path}`.split(/x/)
end
def capture_size_after_retrieve_from_cache(cache_name)
model.header_width, model.header_height = `identify -format "%wx%h" #...@file.path}`.split(/x/)
end
Fixing the bugs (before -> after) and code smell in the solution (using identify directly), we get a working version:
# Somewhere in your uploader:
attr_reader :geometry
after :cache, :capture_size
after :retrieve_from_cache, :capture_size
def capture_size(*args)
img = ::MiniMagick::Image::read(File.binread(@file.file))
@geometry = [img[:width], img[:height]]
end