【问题标题】:CarrierWave / MiniMagick not updating file extension after convertCarrierWave / MiniMagick 转换后不更新文件扩展名
【发布时间】:2022-01-14 16:12:28
【问题描述】:

我正在使用 MiniMagick 和 CarrierWave 在 Rails 5.2 应用程序上处理一些图像。我的目标是将原始图像转换为 jpg,并创建另外两个版本(调整大小)。

我的问题是,虽然“版本”得到了正确处理,但原始文件已被转换,但其扩展名并未更新为 .jpg。例如,如果我通过我的上传器传递this image,我将得到以下三个图像:placeholder-image.pnglarge_placeholder-image.jpgthumb_placeholder-image.jpg(注意第一个图像是原始图像,它的扩展名是.png)。

我不知道为什么会这样,任何帮助将不胜感激

代码如下:

class PhotoUploader < CarrierWave::Uploader::Base
  include CarrierWave::MiniMagick
  process convert: 'jpg'

  version :large do
    process resize_to_fit: [2000, 2000]
  end

  version :thumb do
    process resize_to_fit: [500, nil]
  end
end

也试过这个,导致同样的问题:

class PhotoUploader < CarrierWave::Uploader::Base
  include CarrierWave::MiniMagick

  version :jpg do
    process convert: 'jpg'
  end

  version :large, from_version: :jpg do
    process resize_to_fit: [2000, 2000]
  end

  version :thumb, from_version: :jpg do
    process resize_to_fit: [500, nil]
  end
end

【问题讨论】:

    标签: ruby-on-rails ruby carrierwave minimagick


    【解决方案1】:

    不知道你是否仍然卡住,但诀窍是你需要重写 filename 方法。

    类似

    process convert: 'jpg'
        
          
    def filename
      super.chomp(File.extname(super)) + '.jpg' if original_filename.present?
    end
    

    另一种方法(我将在我自己的应用程序中尝试,以及为什么我在这里偶然发现了你的问题)是按版本覆盖它 - 请参阅 https://github.com/carrierwaveuploader/carrierwave/wiki/How-to:-Customize-your-version-file-names

    【讨论】:

    • 感谢您的回复!我实际上已经使用您提到的其他方法解决了这个问题 - 我将使用我使用的代码为我的问题添加答案。
    【解决方案2】:

    我已经使用版本名称customization 解决了这个问题。请注意,我选择不转换原始文件,这与我最初的方法有点不同。

    这是我实现的代码的 sn-p:

    class PhotoUploader < CarrierWave::Uploader::Base
      include CarrierWave::MiniMagick
    
      version :large do
        process resize_to_fit: [2000, 2000]
        process convert: 'jpg'
    
        def full_filename(for_file = model.file_name.file)
          "large_#{for_file.sub('png', 'jpg')}"
        end
      end
    
      version :thumb do
        process resize_to_fit: [500, nil]
        process convert: 'jpg'
    
        def full_filename(for_file = model.file_name.file)
          "thumb_#{for_file.sub('png', 'jpg')}"
        end
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-22
      • 1970-01-01
      相关资源
      最近更新 更多