Rails Active Storage shrinks images before uploading

Overview

When saving an image to Amazon S3 etc. with Active Storage, upload the image after reducing it.

--Environment - Rails 6.0.3.3 - Active Storageimage_processinglibvips

Implementation

Before saving, replace the tempfile of the attached image (ʻActionDispatch :: Http :: UploadedFile`) with a compressed version.

model
class Event < ApplicationRecord
  has_many_attached :images
end
View
<div class="form-group">
  <%= f.label :images %>
  <%= f.file_field :images, multiple: true, class: 'form-control-file' %>
</div>
Compress & save
@event.images.each do |image|
  image.tempfile = ImageProcessing::MiniMagick.source(image.tempfile).resize_to_fit(1280, 1280).call
end
@event.save

Recommended Posts

Rails Active Storage shrinks images before uploading
[Rails 6] Add images to seed files (using Active Storage)
[Rails API + Vue] Upload and display images using Active Storage
[Rails] How to use Active Storage
[rails6.0.0] How to save images using Active Storage in wizard format
[Active Storage] Validation settings when uploading files
Post / delete multiple images with Active Storage
Introduce Active Storage
About Active Storage
[Rails] Show avatars in posts using Active Storage
How to link images using FactoryBot Active Storage
[Ruby on Rails] Delete s3 images with Active Strage
docker + rails + nginx + webpacker + ssl + action cable + active storage
[Rails] About active hash
[Rails] Introducing Active Hash
[Beginner] About Active Storage