【问题标题】:Rails Carrierwave & Imagemagick, using conditions to resize imageRails Carrierwave 和 Imagemagick,使用条件调整图像大小
【发布时间】:2017-12-24 16:22:04
【问题描述】:

我一直在努力寻找任何教程或问题来解释如何根据用户提供的某些条件上传图像并调整其大小。

我可以使用硬编码值轻松上传和调整图像大小,但我一直坚持使用用户提供的参数从上传器访问。

我希望根据用户检查图像是大还是小,将图像大小调整为 800x600 或 300x300。

为此,我在模型结构中有一个名为“大”的布尔列。

在 Uploader 中,我可以在 store_dir 块中轻松访问模型及其值,但在此块之外的任何地方,任何模型属性都返回为 nil。

这就是我想做的:-

class BannerUploader < CarrierWave::Uploader::Base
    include CarrierWave::MiniMagick
    storage :file
    def store_dir
        "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
    end
    resize_to_fit(800,600) if model.large==true
    resize_to_fit(300,300) if model.large!=true
end

但是这会返回错误 BannerUploader:Class 的未定义局部变量或方法“模型”

如何解决这个问题。

【问题讨论】:

标签: ruby-on-rails imagemagick carrierwave


【解决方案1】:

要处理原始文件,您可以指定自定义方法:

class BannerUploader < CarrierWave::Uploader::Base
  include CarrierWave::MiniMagick
  storage :file
  def store_dir
      "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

  process :process_original_version

  def process_original_version
    if model.large
      resize_to_fit(800,600)
    else
      resize_to_fit(300,300)
    end
  end
end

对于特定版本:

class BannerUploader < CarrierWave::Uploader::Base
  include CarrierWave::MiniMagick
  storage :file
  def store_dir
      "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

  version :normal do
    if model.large
      process resize_to_fit: [800,600]
    else
      process resize_to_fit: [300,300]
    end
  end
end

【讨论】:

    【解决方案2】:

    好的,所以@Alex Kojin 有正确的答案。但是,我也面临另一个问题。当用户提交表单时,图像将始终被调整为小(300x300),因为由于某种原因,图像调整大小过程将首先执行,然后“大”属性将设置为 true。因此,上传者总是将 model.large 设为 false。 所以这就是我不得不改变我的动作控制器的方式

    def create
        @banner=Banner.new
        @banner.large=params[:large]
        @banner.update_attributes(banner_params)
        @banner.save
        redirect_to :back
    end
    

    不确定这是否是正确的方法,但对我有用。

    【讨论】:

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