How to draw text on an image in C#
By FoxLearn 11/15/2024 7:51:51 AM 116
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();
- How to fix 'Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on'
- How to use BlockingCollection in C#
- Calculating the Distance Between Two Coordinates in C#
- Could Not Find an Implementation of the Query Pattern
- Fixing Invalid Parameter Type in Attribute Constructor
- Objects added to a BindingSource’s list must all be of the same type
- How to use dictionary with tuples in C#
- How to convert a dictionary to a list in C#
Categories
Popular Posts
11 Things You Didn't Know About Cloudflare
12/19/2024