Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resize images before uploading with Active Storage (linked with AWS)

I try to use Active Storage with Amazon Web Services, instead of Carrierwave and Cloudinary.

With Carrierwave I had some features that allow to resize images before uploading trough an UploaderController.

But how to do that with Active Storage ?

I try this :

Gemfile :

gem 'aws-sdk-s3', require: false
gem 'image_processing', '~> 1.2'
gem 'mini_magick', '~>4.9'

item.rb

class Item < ApplicationRecord
    has_one_attached :photo
end

I have a form in my view :

<%= f.input :photo, input_html: { accept: ('image') } %>

I get this object as photo :

#<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>

And in my controller :

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

I can't achieve to resize my photo with methods of MiniMagick gem.

Does anybody have any ideas to do that ?

Thanks for your help, Thibault

like image 449
Thibault Avatar asked Dec 17 '18 08:12

Thibault


People also ask

Does S3 optimize images?

You can attach your AWS S3 bucket to ImageKit and start delivering optimized images in just a few minutes.


1 Answers

If params[:item][:photo] is the param from your post you can add

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

With ImageProcessing::Vips (default in rails7)

path = params[:game][:photo].tempfile.path
image = ImageProcessing::Vips.source(path)
result = image.resize_to_limit!(800, 800)
params[:game][:photo].tempfile = result
like image 184
Donapieppo Avatar answered Sep 22 '22 17:09

Donapieppo