【问题标题】:Carrierwave image dimension载波图像尺寸
【发布时间】:2013-10-15 04:14:47
【问题描述】:

如何获取当前载波实例的宽度和高度?

类似这样的:

car_images.each do | image|
  image_tag( image.photo_url, :width => image.photo_width, :height => image.photo_height)
end

很遗憾,image.photo_widthimage.photo_height 无法正常工作。 我需要指定图像的宽度和高度,这是我正在使用的 jquery 插件所必需的。

【问题讨论】:

    标签: ruby-on-rails ruby carrierwave rmagick


    【解决方案1】:

    https://github.com/jnicklas/carrierwave/wiki/How-to:-Get-version-image-dimensionshttps://github.com/jnicklas/carrierwave/wiki/How-to:-Store-the-uploaded-file-size-and-content-type 结合起来,您会得到:

    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
    

    【讨论】:

      【解决方案2】:

      如果使用 Rmagick,您可以很容易地将高度和宽度保存为模型的属性。在 Carrierwave 上传器中:

      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
      

      在你的模型中:

      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
      

      【讨论】:

      • 这适用于新上传 (image_changed?==true) 但如何测量现有附件的尺寸?我似乎无法从控制台访问 get_geometry 方法。我收到“private method 'file' called for #&lt;CarrierWave::Storage::Fog::File:0x00000005225b28&gt;”。
      【解决方案3】:

      或者只使用FastImage。这使得追溯测量附件变得更加容易。

      【讨论】:

      • 仅获取尺寸,Fastimage 比 Imagemagick 快一百倍
      【解决方案4】:

      @JamieD 的回答对我有用,但有一个例外。我用的是 MiniMagick。

      所以我在上传器中添加了类似的内容。

      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
      

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多