Write text to an image using C#.NET

In this post we are going to know how to write a text to an image using C#.NET. It was required in one of the projects that we were working on, the ability to write a dynamic string that would be entered by the user to an image.

Please find below the code that write a text to an image:

using System.Drawing;
using System.Drawing.Imaging;

namespace NB.BlogCode
	public class Program
	 static void Main(string[] args)
            DrawText(Color.Black, Color.White, "Arial", 20, "this is a test text", 250, 250, @"D:/test.jpg");

         public static void DrawText(Color foreColor, Color backColor, string fontName, int fontSize, string txt, int height, int width, string imagePath)
            Bitmap img = new Bitmap(height, width);
            Graphics Gimg = Graphics.FromImage(img);
            Font imgFont = new Font(fontName, fontSize);
            PointF imgPoint = new PointF(5, 5);
            SolidBrush bForeColor = new SolidBrush(foreColor);
            SolidBrush bBackColor = new SolidBrush(backColor);

            Gimg.FillRectangle(bBackColor, 0, 0, width, height);
            Gimg.DrawString(txt, imgFont, bForeColor, imgPoint);
            img.Save(imagePath, ImageFormat.Jpeg);

Share this post

Leave a comment

Previous Post

Next Post