Orchard CMS has very impressive feature called "Orchard.MediaProcessing", which give us the ability to manibulate media files at runtime through predefined set of filters, to create multiple versions of same media file without the need to upload it multiple times, currently, Orchard comes with two prebuilt filters (Resize and Format), and as always, like other Orchard features, you can extend the list of filters to include any type of manibulation filters as you need using the extensibility hooks.
In this post, we will learn how to add a new filter, which frequently asked by the community, aims to add image or text watermark to site images, in next steps we will explian most important parts of the code, while you can download the nuget package from attachments section below (Compatible with Orchard 1.10 and later), or you can browse the full source code of the module on Github.
The default library for all Orchard predefined image processing filters is "ImageResizer", that although it is a great library, but it does not has a good watermark plugin to use in our case, so the choice was to use "ImageProcessor" library instead.
The main reason of using "ImageProcessor" library, that it can apply the watermark image and text using streams without the need to save the image in file system to be able to process it like other libraries, so you can manibulate the context stream directly inside the filter provider even if the file stream is coming from external source (Refer to this documentation for more information).
var result = new MemoryStream();
using (ImageFactory imageFactory = new ImageFactory(preserveExifData: true))
Image = watermarkImage,
Size = new Size(width, height),
Opacity = opacity,
Position = position
context.Media = result;
As you see, "ImageProcessor" watermark maniplulation is based on layers, so you can add any number of layers (Image or Text Layers), as in the previous code snippet, where we are maniplulating the "Media" stream directly through the "imageFactory" to add new "ImageLayer" with specific properties which should be defined by the user through the admin dashboard (You can try the attached module to see how it is working), also we can do the same to add "TextLayer".