knight_rider_watermarkLately I've been using the Dragonfly gem to work with images on my rails models. One of my favorite things about Dragonfly is its chainable image processing language (or DSL) for generating different versions of an image (thumbnail, greyscale, etc). At the core of Dragonfly's DSL is a thin wrapper around ImageMagick which is really handy for common transformations. For more complicated transforms it sure would be nice to extend that language with your own custom processing step, and thankfully Dragonfly makes that really easy too!

For example, recently I needed to generate a low-res watermarked version of an image. The first step—to scale the image down—is easy to do with Dragonfly's existing syntax:


The next step is to overlay a watermark. We want to resize our watermark to fit the source image, and then apply the fitted watermark onto the source image with a given level of transparency (or opacity). This is possible to do with ImageMagick; however, it's a bit more complicated, so this is a good opportunity to implement a custom image processor:

[gist id="6356326da28f883510e0"]

This processor cannot work in a vacuum, however; it must be registered so that Dragonfly can use it with its other processing steps:

[gist id="b3182af2db0357199040"]

Now that Dragonfly knows about our Processor, we can put it together with the scaling step to achieve a low-res watermarked version of any image:


That's it! This technique can be adapted to insert whatever custom ImageMagick transformation you can come up with into Dragonfly's DSL. Pretty sweet!

Building Cool Websites with Vue.js