How to add text to an image with C# in dotnet
Tags: csharp, dotnet, image, imagesharp
Published: 2023-04-11 10:00:24

---
title: How to add text to an image with C# in dotnet
published: true
date: 2023-01-04 00:00:00 UTC
tags: csharp,dotnet,image,imagesharp
canonical_url: https://driesdeboosere.dev/blog/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:

![](https://driesdeboosere.dev/blog/how-to-add-text-to-image-in-dot-net/how-to-add-text-to-image-in-dot-net-01.png)

- And add the text to an image:

![](https://driesdeboosere.dev/blog/how-to-add-text-to-image-in-dot-net/how-to-add-text-to-image-in-dot-net-02.png)

## Create a new application

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

![](https://driesdeboosere.dev/blog/how-to-add-text-to-image-in-dot-net/how-to-add-text-to-image-in-dot-net-03.png)

- Give your project and solution a name:

![](https://driesdeboosere.dev/blog/how-to-add-text-to-image-in-dot-net/how-to-add-text-to-image-in-dot-net-04.png)

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

![](https://driesdeboosere.dev/blog/how-to-add-text-to-image-in-dot-net/how-to-add-text-to-image-in-dot-net-05.png)

## 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](https://www.freeimages.com/photo/aged-papers-1142460).

![](https://driesdeboosere.dev/blog/how-to-add-text-to-image-in-dot-net/how-to-add-text-to-image-in-dot-net-06.jpg)

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

![](https://driesdeboosere.dev/blog/how-to-add-text-to-image-in-dot-net/how-to-add-text-to-image-in-dot-net-08.png)

- 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;

![](https://driesdeboosere.dev/blog/how-to-add-text-to-image-in-dot-net/how-to-add-text-to-image-in-dot-net-09.png)

- Change the _Build Action_ to **Resource**
- Change the _Copy to Output Directory_ to **Copy if newer**

![](https://driesdeboosere.dev/blog/how-to-add-text-to-image-in-dot-net/how-to-add-text-to-image-in-dot-net-10.png)

## 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](https://www.dafont.com/autography.font).

![](https://driesdeboosere.dev/blog/how-to-add-text-to-image-in-dot-net/how-to-add-text-to-image-in-dot-net-07.png)

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

![](https://driesdeboosere.dev/blog/how-to-add-text-to-image-in-dot-net/how-to-add-text-to-image-in-dot-net-11.png)

## 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; }
	}
}
```

- Create a `ResultViewModel` in the **Models/Home** folder

```
namespace AddTextToImage.Mvc.Models.Home
{
    public class ResultViewModel
    {
        public string Path { get; set; }
    }
}
```

- Change the `Index` action method in the `HomeController`

```
public IActionResult Index()
{
	IndexViewModel model = new IndexViewModel();
	return View(model);
}
```

- 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

```

- Add two [SixLabors ImageSharp](https://github.com/SixLabors/ImageSharp) NuGet packages to the project:

```
<>
<>
```

- 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);
}
```

- Inject `IWebHostEnviroment` in the `HomeController` constructor

```
private readonly ILogger _logger;
private readonly IWebHostEnvironment _webHostEnvironment;

public HomeController(ILogger logger, IWebHostEnvironment webHostEnvironment)
{
    _logger = logger;
    _webHostEnvironment = webHostEnvironment;
}
```

- Create a `Result` method in the `HomeController`

```
public IActionResult Result(ResultViewModel model)
{
    return View(model);
}
```

- Create a `Result` View in the **Views/Home** folder

```
@model AddTextToImage.Mvc.Models.Home.ResultViewModel

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

	@ViewData["Title"]
	
		
			
		
	

```

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

```

![](https://driesdeboosere.dev/blog/how-to-add-text-to-image-in-dot-net/how-to-add-text-to-image-in-dot-net-01.png)

- Click on **Create image**
- See the result

![](https://driesdeboosere.dev/blog/how-to-add-text-to-image-in-dot-net/how-to-add-text-to-image-in-dot-net-02.png)

## 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](https://github.com/Drieze/driesdeboosere.dev.demos) here.