Retrieving image height with CarrierWave

2020-05-24 04:45发布

问题:

I need the ability to put the processed image's dimensions.

I have in my ImageUploader class:

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

Is there a way that I could get the image's dimensions similar to this?

height = @picture.image_height(:post)

回答1:

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


回答2:

You can hook onto the :cache and :retrieve_from_cache methods

There is no need to rely on system commands either:

# 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

http://www.glebm.com/2012/05/carrierwave-image-dimensions.html



回答3:

i googled some around a came onto a post with the following:

source link http://groups.google.com/group/carrierwave/browse_thread/thread/c5e93b45bde8a85e?fwc=1&pli=1

class HeaderUploader < CarrierWave::Uploader::Base 
   storage :right_s3 
  def store_dir 
     "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}" 
  end 
  def url 
    ["http://#{s3_bucket}.s3.amazonaws.com/", path].compact.join 
  end 
   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 
  def dimensions 
    "#{model.header_width}x#{model.header_height}" 
  end 
end