Adding custom Active Storage transformations

Curated ago by @jeremysmithco

Description

Out of the box, Active Storage supports a number of transformations, through the image_processing gem. This gem provides a common interface to both MiniMagick (the old standard) and ruby-vips (the new default).

I recently needed the ability to lighten images uploaded via Active Storage (for use as watermarks), but there isn’t a built-in method to do this through the transformations interface. However, I discovered that you can register your own custom ImageProcessing methods like this. (Thanks to this blog post for the approach.)

1
2
3
<% if @document.watermark.attached? %>
  <%= image_tag @document.watermark.variant({ resize_to_limit: [1_000, 1_000], lighten: 0.5 }) %>
<% end %>

Here we can use the custom lighten processing method in combination with other stock transformations (like resize_to_limit) when calling variants.