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

📅 Published 01/04/2023

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

  • Create a ResultViewModel in the Models/Home folder

  • Change the Index action method in the HomeController

  • Change the Index view from the Home folder

  • Add an Index with an [HttpPost] attribute

  • Inject IWebHostEnviroment in the HomeController constructor

  • Create a Result method in the HomeController

  • Create a Result View in the Views/Home folder

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:

  • 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.

An unhandled error has occurred. Reload 🗙