Carrierwave在飞行中调整大小

时间:2013-10-10 17:22:33

标签: ruby-on-rails carrierwave image-resizing on-the-fly ondemand

我正在使用carrierwave,我遇到了这个问题: 假设项目一旦交付,您需要添加一个部分,其中系统中的图像需要以不同的大小显示。我不想为系统中已有的每个图像重新生成新维度。我希望能够在视图需要时生成(并缓存它)。类似于:“/>。如果新的大小500x150已经存在,则返回缓存的url,否则生成它并返回缓存的URL

我非常喜欢Carrierwave但很遗憾没有开箱即用的大小调整功能。每个人都说应该很简单添加这个功能,但我几乎找不到任何东西。唯一接近的是这个上传者https://gist.github.com/DAddYE/1541912 我不得不修改它以使其工作,所以这是我的版本

class ImageUploader < FileUploader
  include CarrierWave::RMagick

  #version :thumb do
  #  process :resize_to_fill => [100,100]
  #end
  #
  #version :thumb_square do
  #  process :resize_to_fill => [100,100]
  #end
  #
  #version :full do
  #  process :resize_to_fit => [550, 550]
  #end


  def re_size(string_size)
    if self.file.nil?
      return self
    end

    begun_at = Time.now
    string_size.gsub!(/#/, '!')
    uploader = Class.new(self.class)
    uploader.versions.clear
    uploader.version_names = [string_size]
    img = uploader.new(model, mounted_as)
    img.retrieve_from_store!(self.file.identifier)
    cached = File.join(CarrierWave.root, img.url)
    unless File.exist?(cached)
      img.cache!(self)

      img.send(:original_filename=, self.file.original_filename)
      size = string_size.split(/x|!/).map(&:to_i)
      resizer = case string_size
                  when /[!]/ then :resize_to_fit
                  # add more like when />/ then ...
                  else :resize_to_fill
                end
      img.send(resizer, *size)
      FileUtils.mv(img.file.file, cached)
      #img.store!
    end
    img
  end

  def extension_white_list
    %w[jpg jpeg gif png]
  end

  def filename
    Digest::MD5.hexdigest(original_filename) << File.extname(original_filename) if original_filename
  end

  def cache_dir
    "#{Rails.root}/tmp/uploads"
  end

  def default_url
    '/general/no-image.png'
  end
end

这个版本的问题显然是在调用re_size(“100x100”)。url时,url会在创建实际调整大小的图像之前生成并返回,从而导致链接断开的页面在任何后续刷新时显示良好。

有谁愿意分享更好的成绩? :)

请不要告诉我切换到Dragonfly。我正在使用Carrierwave,我非常喜欢它。它还与RailsAdmin无缝集成,这也是我项目的一部分。

1 个答案:

答案 0 :(得分:0)

为什么不生成图像的不同版本,例如缩略图?在image_uploader.rb

 # Create different versions of your uploaded files:

 include CarrierWave::RMagick


 version :thumb do
    process :resize_to_limit => [100, 100]
 end

然后在您的视图中调用

 <%= image_tag nameofimage.image_url(:thumb).to_s %>

您可以创建原始图像的多个版本,而无需调整原始图像的大小。处理由RMagick完成,您需要安装。

RMagick要求您拥有ImageMagick,因此您也需要安装它。这些安装和工作可能有点棘手但非常值得。此外,stackoverflow社区已经为这个问题提供了很多帮助。

Error installing Rmagick on Mountain Lion

rmagick gem install "Can't find Magick-config"