Rails foundationSort Order

Rails: Active Storage Image Processing

Image processing is important for every application. You want to serve the right sized image for your page. Let's start by installing the right dependencies.

Image Processing Gem

The image_processing gem depends on a couple of system dependencies we can install them by using

brew install imagemagick vips# orbrew install graphicsmagick

Once installed we can add the gem to our Gemfile

gem 'image_processing', '~> 1.2'

Next lets run

bundle install

This should set up all the dependencies for our application to handle image processing. Be sure to restart your application server if you already have it started.

Displaying the Image

Displaying the image is quite obvious. In our app/views/posts/show.html.erb

# add the following anywhere you wish to display the image<%= image_tag @post.cover_picture %>

This will render our image at the original size. If we would like to display it in the correct size we can use variant

# we use 750x750 as an example try out your own sizes<%= image_tag @post.cover_picture.variant(resize: '750x750') %>

In the official active storage documentation there might be a different example like this.

<%= image_tag @post.cover_picture.variant(resize_to_fit: [750, 750]) %>

However if you run into mogrify unrecognized option resize-to-fit then simply switch to the variant(resize: '750x750')

Handling Missing Images

In the previous episode we covered removing attachments which means in our view we need to handle the case where the attachment no longer exists. In our views we can simply wrap the image_tag with the following.

<% if @post.cover_picture.attachment? %>  <%= image_tag @post.cover_picture.variant(resize: '750x750') %><% end %>

This should take care image displaying and processing for us.