How to draw text on an image in C#
By FoxLearn 1/16/2025 7:21:38 AM 217
To draw text on an image in C#, you can use the System.Drawing namespace, which provides the necessary classes like Graphics, Font, Brush, and Image to work with images and text.
How to draw text on an image in C#?
First, You need to import System.Drawing
and System.Drawing.Imaging
to work with images and drawing operations.
using System; using System.Drawing; using System.Drawing.Imaging;
You can load an image from a file, stream, or create a blank image to work with.
// Load an existing image from file string fileName = "C:\\test.jpg" Image image = Image.FromFile(fileName);
Next, Create a Graphics
object to draw on the image.
Graphics graphics = Graphics.FromImage(image);
You’ll need to specify the font and color for the text.
Font font = new Font("Arial", 20, FontStyle.Bold); Brush brush = new SolidBrush(Color.Black); // Text color (black)
Use the Graphics.DrawString
method to draw the text on the image. You need to specify the text, the font, the brush, and the position where the text will be drawn.
// Draw the text on the image at position (100, 100) graphics.DrawString("C# Programming", font, brush, new PointF(100, 100));
Once you’ve drawn the text, you can save the image back to a file or use it in any other way.
image.Save("C:\image_with_text.jpg", ImageFormat.Jpeg);
Make sure to dispose of the Graphics
and Font
objects to release resources.
// Dispose of resources graphics.Dispose(); font.Dispose(); image.Dispose();
- String to Byte Array Conversion in C#
- How to Trim a UTF-8 string to the specified number of bytes in C#
- How to Save a list of strings to a file in C#
- How to Convert string list to int list in C#
- How to Convert string list to float list in C#
- How to Remove a list of characters from a string in C#
- How to Check if a string contains any substring from a list in C#
- Find a character in a string in C#
Categories
Popular Posts
Regal Admin Dashboard Template
11/18/2024
Horizon MUI Admin Dashboard Template
11/18/2024
How to secure ASP.NET Core with NWebSec
11/07/2024
Responsive Animated Login Form
11/11/2024