'How to add tiling / repeat watermark with ImageSharp?

I want add tiling/repeat watermark to image by using ImageSharp 1.0.0-beta7. I need figure out how many watermarks and how many points where watermark display. Then use DrawText function to draw one by one.

Is there any extension or library to fill tiling / repeat watermark once with ImageSharp ?



Solution 1:[1]

Here's the solution using ImageSharp 2.1, ImageSharp.Drawing 1.0-beta14, and SixLabors.Fonts 1.0-beta16

using SixLabors.Fonts;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Drawing.Processing;
using SixLabors.ImageSharp.Processing;
using Color = SixLabors.ImageSharp.Color;
using PointF = SixLabors.ImageSharp.PointF;

//enumerate all jpeg files
var files = Directory.EnumerateFiles(Environment.CurrentDirectory).Where(x => x.EndsWith(".jpg") || x.EndsWith(".jpeg"));
//make a watermark of the filename on the files
foreach (var file in files)
{
    if (file.Contains(" - Watermark"))
    {
        continue;
    }
    Console.WriteLine($"Working on {file}");
    var original = Path.GetFileNameWithoutExtension(file);
    var directory = Path.GetDirectoryName(file);
    var extension = Path.GetExtension(file);
    var filename = Path.GetFileNameWithoutExtension(file);
    filename += " - Watermark";
    //load file with imagesharp
    using (var image = Image.Load(file))
    {
        var fontColl = new FontCollection().AddSystemFonts();
        FontFamily fontFamily1 = fontColl.Families.FirstOrDefault(x => x.Name == "Arial");
        var font = new Font(fontFamily1, 12, FontStyle.Bold);

        TextOptions textoptions = new(font);

        var drawingoptions = new DrawingOptions();
        drawingoptions.GraphicsOptions.BlendPercentage = 0.5f;
        //find out how big the text is
        var textSize = TextMeasurer.Measure(original, textoptions);

        var pointf = new PointF(0, 0);
        int i = 0;
        //loop over the height of the image
        for (float y = 0; y < image.Height; y += (int)textSize.Height)
        {
            //loop over the width of the image
            for (float x = 0; x <= image.Width; x += (int)textSize.Width)
            {
                

                //draw the text on the image
                pointf = new PointF(x, y);
                //alternate the start of the odd rows to offset the text
                if (i % 2 == 0)
                    pointf.X -= textSize.Width / 2;

                image.Mutate(x => x.DrawText(drawingoptions, original, font, Color.White, pointf));

            }
            i++;
        }
        //save image
        image.Save($"{directory}\\{filename}{extension}");


    }
}
Console.ReadLine();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jason Triplett