Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0613· openaiHugging Face Suzhen/CodeChat

net core SixLabors.ImageSharp 添加文字水印 在图片中心位置

  1. User

    net core SixLabors.ImageSharp 添加文字水印 在图片中心位置

  2. Assistant

    您可以使用SixLabors.ImageSharp库在图片中心位置添加文字水印。以下是一个示例代码:

    using SixLabors.Fonts;
    using SixLabors.ImageSharp;
    using SixLabors.ImageSharp.Drawing.Processing;
    using SixLabors.ImageSharp.PixelFormats;
    using SixLabors.ImageSharp.Processing;
    
    public class Program
    {
        public static void Main()
        {
            using (var image = Image.Load<Rgba32>("path_to_your_image"))
            {
                // 定义字体文件路径和大小
                var font = new FontCollection().Install("path_to_your_font_file").CreateFont(24);
    
                // 设置文字
                var text = "Watermark";
    
                // 计算文字的大小
                var textSize = TextMeasurer.Measure(text, new RendererOptions(font));
    
                // 计算文字的位置,将文字居中放置在图片中心位置
                var posX = (image.Width / 2) - (textSize.Width / 2);
                var posY = (image.Height / 2) - (textSize.Height / 2);
    
                // 在指定位置添加文字水印
                image.Mutate(ctx => ctx.DrawText(new TextGraphicsOptions
                {
                    TextOptions = {
                        Font = font,
                    },
                    WrapTextWidth = image.Width, // 自动换行
                    HorizontalAlignment = HorizontalAlignment.Center, // 水平居中
                    VerticalAlignment = VerticalAlignment.Center, // 垂直居中
                }, text, font, Color.White, new PointF(posX, posY)));
    
                // 保存带有水印的图片
                image.Save("path_to_save_watermarked_image");
            }
        }
    }
    

    请确保将 path_to_your_image 替换为您的图片文件路径,path_to_your_font_file 替换为您的字体文件路径,并将 path_to_save_watermarked_image 替换为要保存带有水印的图片的路径。

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.