gpt4 book ai didi

c# - 将文本添加到图像文件

转载 作者:可可西里 更新时间:2023-11-01 08:57:59 25 4
gpt4 key购买 nike

我需要在图像文件中添加文本。我需要读取一个图像文件(jpg、png、gif)并向其中添加一行文本。

最佳答案

在 GDI+ 中,您可以使用 Image 类读取文件,然后使用 Graphics 类向其中添加文本。像这样的东西:

  Image image = Image.FromFile(@"c:\somepic.gif"); //or .jpg, etc...
Graphics graphics = Graphics.FromImage(image);
graphics.DrawString("Hello", this.Font, Brushes.Black, 0, 0);

如果您想在旧文件上保存文件,代码必须稍作更改,因为 Image.FromFile() 方法会锁定文件,直到它被释放。以下是我想出的:

  FileStream fs = new FileStream(@"c:\somepic.gif", FileMode.Open, FileAccess.Read);
Image image = Image.FromStream(fs);
fs.Close();

Bitmap b = new Bitmap(image);
Graphics graphics = Graphics.FromImage(b);
graphics.DrawString("Hello", this.Font, Brushes.Black, 0, 0);

b.Save(@"c:\somepic.gif", image.RawFormat);

image.Dispose();
b.Dispose();

虽然我会非常彻底地测试它:)

关于c# - 将文本添加到图像文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/709414/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com