在 ActiveStorage 中使用变体选项后如何保存图像副本。

rai*_*bie 2 ruby-on-rails rails-activestorage

我在使用 ActiveStorage 时遇到了这个问题,我需要处理图像,我的要求是保存处理过的图像并在裁剪和其他转换后将其附加到新模型。

Geo*_*orn 5

ActiveStorage::Blob#variant适应不同的用例,所以ActiveStorage::Variation直接处理。下面假设最新的 Rails master 而不是 Rails 5.2:

variation = ActiveStorage::Variation.new(resize_to_fit: [100, 100], crop: true)

message.header_image.open do |input|
  variation.transform(input, format: "png") do |output|
    message.cropped_header_image.attach \
      io: output,
      filename: "#{message.header_image.filename.base}.png",
      content_type: "image/png"
  end
end
Run Code Online (Sandbox Code Playgroud)


Fai*_*han 5

@George 有一个很好的答案,但我仍然会提到我的答案,根据我对你的问题的理解,它应该与 Rails 5.2 一起使用,

创建一个临时文件,然后先获取该文件,如果它在您的云存储中,如果不在您的云存储中,则不需要这部分,在这种情况下只需使用 blob 获取路径即可。

path = Rails.root.join('tmp', ModelVariable.main_image.blob.filename.to_s).to_s
File.open(path, 'wb') do |file|
  file.write(ModelVariable.main_image.blob.download)
end
Run Code Online (Sandbox Code Playgroud)

进行您的定制

customize_image = MiniMagick::Image.open(path)
customize_image.crop(crop_params)
Run Code Online (Sandbox Code Playgroud)

将其附加到您想要的不同模型上

file = File.open(customize_image.path)
filename = Time.zone.now.strftime("%Y%m%d%H%M%S") + ModelVariable.main_image.blob.filename.to_s
NewModelVaribale.customized_image.attach(io: file, filename: filename)
Run Code Online (Sandbox Code Playgroud)

保存

customized_product.save
Run Code Online (Sandbox Code Playgroud)

希望这对你有用:)