Carrierwave和mini_magick查找宽度和高度

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

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

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

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 

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

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

在运行时使用RMagickMiniMagick计算图像height / width 缺点

  • 它的CPU密集
  • 它需要Internet来获取图像并计算尺寸。
  • 这是一个缓慢的过程

仅供参考您还可以在jQuery的帮助下使用与标签关联的load事件来计算图像完全加载后的图像HeightWidth

例如

 $(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()图像时不会触发load() 。 当图像位于用户的浏览器cache时,这很容易发生。

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

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

就我而言,型号名称是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

请参阅此处的参考 。