Carrierwave和mini_magick找到宽度和宽度高度

时间:2010-12-15 19:52:01

标签: ruby-on-rails imagemagick ruby-on-rails-3

经过一番调查后,我决定在我的新rails3应用上使用Carrierwave和mini_magick。

我已经设置好了它完美无缺。但是我有一个问题。我希望能够访问宽度和高度,所以我可以正确地形成html。但是,没有用于获取此信息的默认数据。由于它存储数据的方式,我无法想到任何可以将其添加到数据库的方式。

有人可以提出任何提示或想法吗?它甚至可能吗?

4 个答案:

答案 0 :(得分:14)

class Attachment
  mount_uploader :file, FileUploader

  def image
    @image ||= MiniMagick::Image.open(file.path)
  end
end

并像这样使用它:

Attachment.first.image['width'] # => 400
Attachment.first.image['height'] # => 300

答案 1 :(得分:2)

仅仅是为了记录,我使用了类似的解决方案,但使用Mongo GridFS的文件,在这里:

  def image
    @image ||= MiniMagick::Image.read(Mongo::GridFileSystem.new(Mongoid.database).open(file.path, 'r'))
  end

答案 2 :(得分:0)

在运行时使用heightwidth计算图片RMagick / MiniMagick

缺点

  • CPU密集型
  • 要求互联网获取图像并计算尺寸。
  • 这是一个缓慢的过程
  

仅供参考你还可以在之后计算图像HeightWidth   使用与之关联的load事件完全加载图像   在jQuery的帮助下标记<img>

例如

$(document).ready(function(){   
   var $image = $('.fixed-frame img');
   $image.load(function(){
      rePositionLogo($image);
   });

  if($image.prop('complete')){
    rePositionLogo($image);
  }

});

function rePositionLogo($image){
  var height = $image.height();
  var width = $image.width();
  if (width > height) {
    $image.parents('.header').addClass('landscape');
    var marginTop = (105 - $image.height())/2;
    $image.css('margin-top', marginTop + 'px')
  }else{
    $image.parents('.header').addClass('portrait');
  }
}

请注意,因为在加载图像时不会触发load()。当图像位于用户的浏览器cache中时,这可以很容易地发生。

您可以使用$('#myImage').prop('complete')检查图像是否已加载,在加载图像时返回true

答案 3 :(得分:0)

我认为最好的方法是将图像尺寸存储在模型(数据库)中。

就我而言,型号名称为attachment。然后我创建了一个迁移:

rails g migration add_dimensions_to_attachments image_width:integer image_height:integer

之后,运行迁移:

rake db:migrate

在我的Image Uploader文件app/uploaders/image_uploader.rb中,我有:

class ImageUploader < CarrierWave::Uploader::Base

    include CarrierWave::MiniMagick

    process :store_dimensions

    private

    def store_dimensions
      if file && model
        model.image_width, model.image_height = ::MiniMagick::Image.open(file.file)[:dimensions]
      end
    end
  end

使用此功能,图像尺寸将保存在上传步骤中。

要获取尺寸,我只需运行attachment.image_widthattachment.image_height

请参阅reference here

相关问题