C#在图片上添加文字代码
时间: 2023-09-05 09:10:59 浏览: 67
你可以使用C#的System.Drawing命名空间中的Graphics类来在图片上添加文字,具体代码如下:
```
using System.Drawing;
using System.Drawing.Imaging;
// 加载图片
Image image = Image.FromFile("image.jpg");
// 创建Graphics对象
Graphics graphics = Graphics.FromImage(image);
// 设置文字样式
Font font = new Font("Arial", 20);
SolidBrush brush = new SolidBrush(Color.Black);
// 绘制文字
graphics.DrawString("Hello World", font, brush, new PointF(10, 10));
// 保存图片
image.Save("output.jpg", ImageFormat.Jpeg);
// 释放资源
graphics.Dispose();
image.Dispose();
```
其中,需要替换的部分是图片路径、文字内容、文字样式和输出路径。
相关问题
C# 在Bitmap灰度图上添加文字的代码
以下是使用 C# 在 Bitmap 灰度图上添加文字的示例代码:
```csharp
using System;
using System.Drawing;
using System.Drawing.Imaging;
public class Program
{
public static void Main(string[] args)
{
// 加载原始灰度图像
Bitmap greyImage = new Bitmap("grey_image.bmp");
// 创建一个可绘制的图像副本
Bitmap imageWithText = new Bitmap(greyImage.Width, greyImage.Height);
// 创建一个 Graphics 对象用于在图像上绘制文本
using (Graphics graphics = Graphics.FromImage(imageWithText))
{
// 复制原始图像到新的图像上
graphics.DrawImage(greyImage, 0, 0);
// 设置要绘制的文本
string text = "Hello, World!";
Font font = new Font("Arial", 12, FontStyle.Regular);
Brush brush = new SolidBrush(Color.White);
// 在图像上绘制文本
graphics.DrawString(text, font, brush, new PointF(10, 10));
}
// 保存修改后的图像
imageWithText.Save("image_with_text.bmp", ImageFormat.Bmp);
}
}
```
在上述代码中,我们首先加载了一个灰度图像 `grey_image.bmp`。然后,我们创建了一个与原始图像大小相同的新图像 `imageWithText`。接下来,我们使用 `Graphics` 对象在新图像上绘制文本。最后,我们将修改后的图像保存为 `image_with_text.bmp`。
请确保将实际的灰度图像文件路径替换为代码中的文件路径,以便代码能够正确加载和保存图像。还可以根据需要调整文本的位置、字体和颜色等参数。
c#一种高效图片上添加文字方法
在 C# 中,如果你需要在图片上高效地添加文字,可以使用 `Graphics` 对象的 `DrawString` 方法。为了提高性能,你可以使用 `Graphics` 对象的 `TextRenderingHint` 属性设置文本呈现质量,并使用 `StringFormat` 对象设置文本布局选项。
下面是一个示例代码,演示如何高效地在图片上添加文字:
```csharp
using System;
using System.Drawing;
using System.Drawing.Imaging;
public class Program
{
public static void Main(string[] args)
{
// 加载原始图片
Bitmap image = new Bitmap("image.bmp");
// 创建一个绘制图像的 Graphics 对象
using (Graphics graphics = Graphics.FromImage(image))
{
// 设置文本呈现质量为高质量
graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;
// 设置文本布局选项
StringFormat stringFormat = new StringFormat();
stringFormat.Alignment = StringAlignment.Center;
stringFormat.LineAlignment = StringAlignment.Center;
// 设置要绘制的文本
string text = "Hello, World!";
Font font = new Font("Arial", 12, FontStyle.Regular);
Brush brush = Brushes.White;
// 在图像上绘制文本
graphics.DrawString(text, font, brush, image.Width / 2, image.Height / 2, stringFormat);
}
// 保存修改后的图像
image.Save("image_with_text.bmp", ImageFormat.Bmp);
}
}
```
在上述代码中,我们首先加载了原始图片 `image.bmp`。然后,我们创建一个 `Graphics` 对象,用于在图像上进行绘制操作。为了提高文本呈现质量,我们将 `TextRenderingHint` 属性设置为 `AntiAliasGridFit`。通过 `StringFormat` 对象,我们设置文本的布局选项,例如居中对齐。然后,我们设置要绘制的文本、字体和画刷颜色等。最后,我们使用 `DrawString` 方法在图片上绘制文本。
确保将实际的图片文件路径替换为代码中的文件路径,以便代码能够正确加载和保存图像。你还可以根据需要调整文本的位置、字体和颜色等参数。这种方法可以在保持高效性能的同时,在图片上添加文字。