Using the OnInit event to configure pipeline elements

Branched Pipeline Resize Advanced

What if we want to adjust pipeline element settings depending on the actual input data? In most cases you have access to the source element, but in more sophisticated scenarios the pipeline may be large, and it may be hard to track all possible changes of the image parameters. Or you may decide to split the pipeline assembly logic into several methods. In this case, it is possible to change pipeline element settings from an OnInit event handler. You get the actual image parameters that the element receives from its source, and change the properties according to those parameters. In this example, we'll scale the original image by a factor of 2.5 while preserving its aspect ratio, and place a watermark image in the center. The watermark image will be half the size of the bottom image.

You can read more information about pipelines in the documentation.

Сode Snippet

// Create pipeline elements
using (var reader = ImageReader.Create("Venice.jpg"))
using (var resize = new Resize())
using (var writer = ImageWriter.Create("OnInitWatermark.jpg"))
{
    // Configure the resize element based on the input image size
    resize.OnInit += (sender, e) =>
    {
        var resizeSender = sender as Resize;
        resizeSender.Width = (int)(e.ImageParams.Width / 2.5f);
        resizeSender.Height = (int)(e.ImageParams.Height / 2.5f);
        resizeSender.ResizeMode = ResizeMode.Resize;
        resizeSender.InterpolationMode = ResizeInterpolationMode.Anisotropic9;
    };

    // Create pipeline elements for the watermark
    using (var topReader = ImageReader.Create("Stamp.png"))
    using (var topResize = new Resize(200, 200, ResizeInterpolationMode.High))
    using (var combiner = new Combiner(CombineMode.Alpha, (topReader + topResize).Build()))
    {
        // Configure the topResize element based on the resized base image size
        topResize.OnInit += (sender, e) =>
        {
            var topResizeSender = sender as Resize;
            topResizeSender.ResizeMode = ResizeMode.Fit;
            topResizeSender.Width = resize.Width / 2;
            topResizeSender.Height = resize.Height / 2;

            resize.InterpolationMode = ResizeInterpolationMode.Anisotropic9;
        };

        // Configure the combiner element to center the watermark
        combiner.OnInit += (sender, e) =>
        {
            var args = e as CombinerOnInitEventArgs;
            var combinerSender = sender as Combiner;
            combinerSender.X = (args.ImageParams.Width - args.TopImageParams.Width) / 2;
            combinerSender.Y = (args.ImageParams.Height - args.TopImageParams.Height) / 2;
        };

        // Run the pipeline
        Pipeline.Run(reader + resize + combiner + writer);
    }
}

Input

Venice.jpg

Stamp.png

Output

OnInitWatermark.jpg

For AI-assisted development: Download Graphics Mill Code Samples XML Catalog