如何在使用 Active Storage(与 AWS 链接)上传之前调整图像大小

Thi*_*ult 8 amazon-s3 minimagick rails-activestorage

我尝试将 Active Storage 与 Amazon Web Services 一起使用,而不是 Carrierwave 和 Cloudinary。

使用 Carrierwave,我有一些功能可以在通过 UploaderController 上传之前调整图像大小。

但是如何使用 Active Storage 做到这一点?

我试试这个:

宝石文件:

gem 'aws-sdk-s3', require: false
gem 'image_processing', '~> 1.2'
gem 'mini_magick', '~>4.9'
Run Code Online (Sandbox Code Playgroud)

项目.rb

class Item < ApplicationRecord
    has_one_attached :photo
end
Run Code Online (Sandbox Code Playgroud)

我认为有一个表格:

<%= f.input :photo, input_html: { accept: ('image') } %>
Run Code Online (Sandbox Code Playgroud)

我把这个对象作为照片:

#<ActiveStorage::Attached::One:0x00005641d296e1b8 @name="photo", @record=#<Item id: nil, name: "test0941", verbe: "To Lend", collection_id: nil, created_at: nil, updated_at: nil, price_cents: 0, description: "", category_id: 78, photo: nil>, @dependent=:purge_later>
Run Code Online (Sandbox Code Playgroud)

在我的控制器中:

@item = Item.new(item_params)
@item.photo.combine_options do |b|
    b.resize "250x200>"
end
Run Code Online (Sandbox Code Playgroud)

我无法使用 MiniMagick gem 的方法来调整我的照片大小。

有没有人有任何想法可以做到这一点?

谢谢你的帮助,蒂博

Don*_*ppo 8

如果 params[:item][:photo] 是您帖子中的参数,您可以添加

  image = MiniMagick::Image.new(params[:item][:photo].tempfile.path)
  image.resize "250x200>"
Run Code Online (Sandbox Code Playgroud)

  • 这是可行的,但就我而言,我必须从 item_params 中删除 :photo ,应用上面的逻辑,然后使用 @item.photo.attach(params[:item][:photo]) 附加照片。 (3认同)