我想使用 ImageSharp 1.0.0-beta7 为图像添加平铺/重复水印。 我需要弄清楚水印显示多少个水印和多少个点。然后使用绘图文本功能逐个绘制。
是否有任何扩展名或库可以使用 ImageSharp 填充平铺/重复水印一次?
以下是使用 ImageSharp 2.1、ImageSharp.Drawing 1.0-beta14 和 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();