Quite often the problem arises to put a watermark on the images on the site. Usually, most developers do not see the problem (many PHP CMS pull it out of the box), but in the world of Rails and the RefineryCMS engine everything is not so smooth.
Refinery uses
Dragonfly (a special image-based gem for Rack and on-the-fly image processing) and there may be some difficulties.
Under the cut described how to make a watermark on the image using the overlay image with a watermark on the main image in RefineryCMS.
Of course you need a picture with a transparent background png extension. Call it watermark.png and place it in the public / project directory.
')
Now how to make the sign overlap. Dragonfly perfectly supports image processors. The basics of processing are described in the
documentation .
So let's make our own image processing class, which will impose a watermark:
class ImageProcessor def watermark(temp_object) tempfile = new_tempfile args = " -dissolve 50% -gravity south
The main idea for creating processors for Dragonfly is taken
from here . Now we will sort the code.
The class contains 2 methods.
The new_tempfile method creates a temporary file - it will be the “output” (this is the result of the image overlay operation) and is used in the ImageMagick command.
The watermark method is accordingly our watermark adding method. Everything is simple here: the temp_object argument is a dragonfly object of the image. Next, we create a temporary file and write the arguments for the composite command from ImageMagick, which will give us an overlay of images. This is a simple and not optimized version, so the path to the watermark.png file is indicated directly here. Arguments:
-dissolve 50% adds transparency.
-gravity south bottom placement.
# {Rails.root} /public/watermark.png - path to the file with the watermark.
# {temp_object.path} - path to the source image.
# {tempfile.path} - the path to our temporary file. It is the latter that will contain the final “glued” image.
Now we need to connect our class for processing to the application. You can create a separate config / initializer / dragonfly.rb file with the following contents:
app = Dragonfly[:refinery_images] app.processor.register(ImageProcessor)
The first line receives the so-called "application" of Dragonfly from RefineryCMS, the second line directly registers our class.
Now you can use it like this:
<%= image_tag image.thumbnail('800x600#').process(:watermark).url %>
Our picture will be displayed with a watermark. Thus, the process method from Dragonfly can work with any registered processors.
This article on the example of RefineryCMS shows how you can quickly and simply add your image processor to Dragonfly. You can use it without Refinery with other great features from ImageMagick.