Writing text to an image using C#

April 2017 ยท 2 minute read

A functioning example can be found here.

Below is a demonstration of how to write text to an image (jpeg) using C# and a custom font.

ImageWriter Class

using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.Drawing.Text; namespace WritingTextOnImage { public class ImageWriter { public void WriteTextToImage(Bitmap image, string savePath, string textToWrite, FontFamily fontFamily) { using (var graphics = Graphics.FromImage(image)) { graphics.SmoothingMode = SmoothingMode.AntiAlias; // Image is 444 x 248 pixels, this should place text center PointF writeLocation = new PointF(222f, 124f); var format = new StringFormat { Alignment = StringAlignment.Center }; using (var font = new Font(fontFamily, 15, FontStyle.Regular)) { graphics.DrawString(textToWrite, font, Brushes.White, writeLocation, format); } image.Save(savePath, ImageFormat.Jpeg); } } public Bitmap LoadImage(string imagePath) { Bitmap image = new Bitmap(imagePath); return image; } public FontFamily LoadFont(string fontPath, string fontName) { PrivateFontCollection fonts = new PrivateFontCollection(); fonts.AddFontFile(fontPath); FontFamily font = fonts.Families[0]; return font; } } }

These are methods to load up the image and font to be passed in as parameters to WriteTextToImage, the method actually writing the string to the image file. The resulting bitmap can also be directed elsewhere and used from memory instead of saving to a file once the string is written.

Using the ImageWriter

using System; using System.Drawing; using System.IO; namespace WritingTextOnImage { class Program { static void Main(string[] args) { string rootProjectPath = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory).Parent.Parent.Parent.FullName; string imagePath = Path.Combine(rootProjectPath + "\\prometheus.jpg"); string fontPath = Path.Combine(rootProjectPath + "\\Chunkfive.otf"); string savePath = Path.Combine(rootProjectPath + "\\new_prometheus.jpg"); var imageWriter = new ImageWriter(); Bitmap image = imageWriter.LoadImage(imagePath); FontFamily font = imageWriter.LoadFont(fontPath, "chunkfive"); imageWriter.WriteTextToImage(image, savePath, "Prometheus", font); } } }

Quick example of using the ImageWriter class with a console program.