I am trying to use ImageProcessor / MiniMagick to resize images before they are saved to the database of my Rails 5.2 app. I am able to save the image, but this image is not resized before saving and there is no error thrown. I'm also using Trix to process and output the images.
Here is what I have set up so far:
image_uploader.rb
require "image_processing/mini_magick"
class ImageUploader < Shrine
Attacher.derivatives do |original|
magick = ImageProcessing::MiniMagick.source(original)
{
resized: magick.resize_to_limit!(600, 600)
}
end
end
shrine.rb (I've included the following line in my shrine.rb file)
Shrine.plugin :derivatives
photos_controller.rb (relevant code from the photos_controller.rb file)
def create
@photo = Photo.new(photo_params)
@photo.valid?
@photo.image_derivatives! if @photo.image_changed? # creates derivatives
respond_to do |format|
if @photo.save
format.html { redirect_to @photo, notice: 'Photo was successfully created.' }
format.json { render :show, status: :created, location: @photo }
else
format.html { render :new }
format.json { render json: @photo.errors, status: :unprocessable_entity }
end
end
end
The code seems to be working from what I see in the database. Console log looks like this:
2.6.1 :014 > photo.image_derivatives
=> {:resized=>#<ImageUploader::UploadedFile storage=:store id="b234085e9502c39f23edb84bced89ee0.png" metadata={"filename"=>"image_processing20210103-23514-zyeyzg.png", "size"=>94105, "mime_type"=>"image/png"}>}
2.6.1 :015 > photo.image(:resized)
=> #<ImageUploader::UploadedFile storage=:store id="b234085e9502c39f23edb84bced89ee0.png" metadata={"filename"=>"image_processing20210103-23514-zyeyzg.png", "size"=>94105, "mime_type"=>"image/png"}>
2.6.1 :017 > photo.image(:resized).size
=> 94105
2.6.1 :018 > photo.image(:resized).mime_type
=> "image/png"
When I pull up a saved record, I can find information that makes me think its working, but there is no resize when I look at it in the view. Any thoughts? ... let me know if I should provide more information.
Though it is not exactly the answer that I was looking for, one way to handle this is was through css. I added the following to my css file and it worked great. Nothing is changing with the way the file is saved on the backend, but the appearance in the browser is what I'm looking for: