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; }
}
}
- 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 theHomeController
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";
}
<form method="post">
<div class="mb-3">
<label for="exampleInputText" class="form-label">Text</label>
<textarea class="form-control" id="exampleInputText" aria-describedby="inputHelp" asp-for="Text"></textarea>
<div id="inputHelp" class="form-text">We'll never share your text with anyone else and do not store your text.</div>
</div>
<button type="submit" class="btn btn-primary">Create image</button>
</form>
- Add two SixLabors ImageSharp NuGet packages to the project:
<PackageReference Include="SixLabors.ImageSharp" Version="2.1.3" />
<PackageReference Include="SixLabors.ImageSharp.Drawing" Version="1.0.0-beta15" />
- 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 theHomeController
constructor
private readonly ILogger<HomeController> _logger;
private readonly IWebHostEnvironment _webHostEnvironment;
public HomeController(ILogger<HomeController> logger, IWebHostEnvironment webHostEnvironment)
{
_logger = logger;
_webHostEnvironment = webHostEnvironment;
}
- Create a
Result
method in theHomeController
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";
}
<div class="container">
<div class="row"><h1>@ViewData["Title"]</h1></div>
<div class="row">
<div class="col-md-8 offset-md-2">
<img data- src="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==" data-src="/blog/how-to-add-text-to-image-in-dot-net/@Model.Path" class="img-fluid" />
</div>
</div>
</div>
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.
- 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.