carrierwave:基于图像属性创建版本

时间:2015-02-24 19:30:59

标签: ruby-on-rails ruby carrierwave

我想保留上传的图像高达700像素。 如果任何图像变大,我使用以下代码来获得新的宽度。

这是我的上传程序文件。

def store_dimensions
if file && model
  width, height = ::MiniMagick::Image.open(file.file)[:dimensions]
        if width>700
              return 700
        else
              return width
        end
end

然后我创建了一个名为best_fit

的版本
process :store_dimensions
version :best_fit do
  process :resize_to_fill => [store_dimensions,200]
end

无法找到store_dimensions方法。另一方面,如果我在声明store_dimensions方法时使用self关键字,那么它可以工作,但是然后"文件"标识符将成为未知实体。

如何获取上传图片的价值,并据此我可以创建它的新版本。

2 个答案:

答案 0 :(得分:1)

以下代码今天保存了我的屁股。我很高兴我解决了它。

def store_dimensions
     if file && model
      width, height = ::MiniMagick::Image.open(file.file)[:dimensions]
        if width>700
              Rails.logger.info "#{width}"
              finalHeight=((700*height)/width)
              self.class.version :best_fit do
                process :resize_to_fill => [700,finalHeight]
              end

        else
              Rails.logger.info "#{width}"
              self.class.version :best_fit do
                process :resize_to_fill => [width,height]
              end
        end
      end
end

#run the store_dimensions methods
  process :store_dimensions

答案 1 :(得分:0)

对于任何迷路的流浪者,这就是您要寻找的东西:

class Uploader
  version :my_version do
    process :my_processor
  end

  def my_processor
    # model is available here!

    manipulate! do |img|
      img.combine_options do |cmd|
        cmd.resize [model.width, model.height].join('x')
      end

      img
    end
  end
end

custom process method

的示例