DEV Community

Dries Deboosere
Dries Deboosere

Posted on • Originally published at driesdeboosere.dev on

How to add text to an image with C# in dotnet

Demo

In this demo, we will add some text to an existing image.

  • We type some Lorem Ipsum text in a textarea:

  • And add the text to an image:

Create a new application

  • Create a new dotnet application, in this demo, we'll use an ASP.NET Core MVC project

  • Give your project and solution a name:

  • Choose your framework, in my case it's .NET6.0, and click on Create

Choosing an image

  • Time for us to choose an image. I found a free image online from an aged paper that you can download here.

  • Now it's time to create a folder in our project. Give this folder the name of Resources.
  • Copy the image to this folder

  • This image needs to be built as a resource and needs to be copied to the output directory. So right-click the image and choose properties;

  • Change the Build Action to Resource
  • Change the Copy to Output Directory to Copy if newer

Choose a font

  • Now it's time to choose a font. Because the image is an aged paper we'll use a handwriting font. For this demo, we'll use the Autography font that you can download here.

  • Place the otf-file in the Resources folder and change the Build Action to Resource and the Copy to Output Directory to Copy if newer.

Add text to image with C

Finally, the moment where we can write some code!

  • Create an IndexViewModel in the Models/Home folder
namespace AddTextToImage.Mvc.Models.Home
{
    public class IndexViewModel
    {
        public string? Text { get; set; }
    }
}
Enter fullscreen mode Exit fullscreen mode
  • Create a ResultViewModel in the Models/Home folder
namespace AddTextToImage.Mvc.Models.Home
{
    public class ResultViewModel
    {
        public string Path { get; set; }
    }
}
Enter fullscreen mode Exit fullscreen mode
  • Change the Index action method in the HomeController
public IActionResult Index()
{
    IndexViewModel model = new IndexViewModel();
    return View(model);
}
Enter fullscreen mode Exit fullscreen mode
  • Change the Index view from the Home folder
@model AddTextToImage.Mvc.Models.Home.IndexViewModel

@{
    ViewData["Title"] = "Home Page";
}


        Text

        We'll never share your text with anyone else and do not store your text.

    Create image

Enter fullscreen mode Exit fullscreen mode
<>
<>
Enter fullscreen mode Exit fullscreen mode
  • Add an Index with an [HttpPost] attribute
[HttpPost]
public IActionResult Index(IndexViewModel model)
{
    var downloadsPath = string.Empty;
    using (var img = SixLabors.ImageSharp.Image.Load(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Resources", paper.jpg")))
    {
        FontCollection collection = new();
        var path = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Resources")); // Path to the Resources folder
        FontFamily family = collection.Add(Path.Combine(path, "Autography.otf")); // Path incl filename for our font
        Font font = family.CreateFont(80, FontStyle.Regular); // Fontsize is 80 and Fontstyle is Regular

        // The options are optional
        TextOptions options = new(font)
        {
            Origin = new PointF(150, 100), // Set the rendering origin with the x and y coordinates
            TabWidth = 8, // A tab renders as 8 spaces wide
            WrappingLength = 1400, // Greater than zero so we will word wrap at 1400 pixels wide
            HorizontalAlignment = HorizontalAlignment.Left,
        };

        IBrush brush = Brushes.Solid(Color.Black); // Font color

        string text = model.Text;

        downloadsPath = Path.Combine(_webHostEnvironment.WebRootPath, "images", "paper-with-text.jpg");

        img.Mutate(x => x.DrawText(options, text, brush)); // Write text on image
        img.Save(Path.Combine(downloadsPath)); // Save image to a folder
    }
    ResultViewModel resultModel = new ResultViewModel();
    resultModel.Path = "/images/paper-with-text.jpg";
    return RedirectToAction("Result", resultModel);
}
Enter fullscreen mode Exit fullscreen mode
  • Inject IWebHostEnviroment in the HomeController constructor
private readonly ILogger _logger;
private readonly IWebHostEnvironment _webHostEnvironment;

public HomeController(ILogger logger, IWebHostEnvironment webHostEnvironment)
{
    _logger = logger;
    _webHostEnvironment = webHostEnvironment;
}
Enter fullscreen mode Exit fullscreen mode
  • Create a Result method in the HomeController
public IActionResult Result(ResultViewModel model)
{
    return View(model);
}
Enter fullscreen mode Exit fullscreen mode
  • Create a Result View in the Views/Home folder
@model AddTextToImage.Mvc.Models.Home.ResultViewModel

@{
    ViewData["Title"] = "Paper with our text";
}

    @ViewData["Title"]






Enter fullscreen mode Exit fullscreen mode

Run our application

Now it's time to run our application, so start the project.

  • Enter some text in the text-area. Some Lorem Ipsum by example:

Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. 

Enter fullscreen mode Exit fullscreen mode

  • Click on Create image
  • See the result

Tweaks

You can tinker around with all the different settings that the ImageSharp package offers, you can change by example

  • font size
  • font family
  • font type
  • font color
  • where the text needs to be aligned
  • horizontal alignment
  • ...

Source

You can find the GitHub repository here.

Top comments (0)