📜  c#boundingbox text - C# (1)

📅  最后修改于: 2023-12-03 14:39:48.299000             🧑  作者: Mango

C# BoundingBox Text

In computer graphics and image processing, a bounding box is a rectangle that encloses a set of object or region of interest in an image. In C#, System.Drawing namespace provides Rectangle struct to represent a bounding box. It defines the position and size of a rectangle by its coordinates and width and height attributes.

In this article, we'll discuss how to draw bounding box text using C#.

1. Create a Bitmap Object

First, we need to create a Bitmap object that represents the image we want to draw bounding box text on.

Bitmap bmp = new Bitmap("image.jpg");

In this example, we assume that there is an image named "image.jpg" in the root directory of the application.

2. Create a Graphics Object

Next, we need to create a Graphics object that represents the drawing surface of the Bitmap object we just created.

Graphics graphics = Graphics.FromImage(bmp);

We can use this graphics object to draw lines, shapes or text on the Bitmap.

3. Draw Bounding Box

To draw a bounding box on the Bitmap, we use the Rectangle struct to define the coordinates and size of the rectangle.

Rectangle rect = new Rectangle(10, 10, 100, 100);
Pen pen = new Pen(Color.Red, 2);
graphics.DrawRectangle(pen, rect);

In this example, we define a rectangle with its top-left corner at (10, 10) with a width of 100 pixels and a height of 100 pixels. We use a red pen with a thickness of 2 pixels to draw the rectangle.

4. Draw Bounding Box Text

To draw text inside the bounding box, we can use the DrawString method of the Graphics object. This method takes a string, a font, a brush and a rectangle as parameters.

string text = "Hello World";
Font font = new Font("Arial", 12);
SolidBrush brush = new SolidBrush(Color.White);
graphics.DrawString(text, font, brush, rect);

In this example, we draw the text "Hello World" using Arial font with a size of 12 points and white color inside the bounding box we defined earlier.

5. Save Bitmap

Finally, we need to save the Bitmap object into an image file. We can use the Save method of the Bitmap object to do this.

bmp.Save("output.png", ImageFormat.Png);

In this example, we save the Bitmap object as a PNG image named "output.png" in the root directory of the application.

Conclusion

That's it. We've learned how to draw bounding box text in C# using System.Drawing namespace. We use the Rectangle struct to define the bounding box and Graphics object to draw text inside it. Finally, we save the image in a file using the Bitmap object.