SixLabors Image Sharp How to Write text to Image c#

2k Views Asked by At

I have searched for a long time. I know it is part of the extended package, but I cannot seem to find any examples. Even a hello world example on how to write text to an Image Sharp image. Thanks for any help.

public Image DragImage {
    get {
        SixLabors.ImageSharp.Image<Rgba32> ri = new((int)rect.Width, (int)rect.Height);
        //FieldName on the ri Image just created
        return ri;
    } 
}
1

There are 1 best solutions below

0
On

Here are the NuGet packages you'll want to reference:

  1. SixLabors.Fonts
  2. SixLabors.ImageSharp
  3. SixLabors.ImageSharp.Drawing

And here's an example code to draw some text on an image:

using SixLabors.Fonts;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Drawing.Processing;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;

const string text = "Sample Text";
const float TextPadding = 18f;
const string TextFont = "Roboto";
const float TextFontSize = 64f;

var image = await Image.LoadAsync("source-filename.jpg");

FontFamily fontFamily;

if (!SystemFonts.TryGet(TextFont, out fontFamily))
    throw new Exception($"Couldn't find font {TextFont}");

var font = fontFamily.CreateFont(TextFontSize, FontStyle.Regular);

var options = new TextOptions(font)
{
    Dpi = 72,
    KerningMode = KerningMode.Normal
};

var rect = TextMeasurer.Measure(text, options);

image.Mutate(x => x.DrawText(
    text,
    font,
    new Color(Rgba32.ParseHex("#FFFFFFEE")),
    new PointF(image.Width - rect.Width - TextPadding,
            image.Height - rect.Height - TextPadding)));

await image.SaveAsJpegAsync("output-filename.jpg");