将文本文件内容另存为图像
本文关键字:另存为 图像 文本 文件 | 更新日期: 2024-09-23 14:16:18
我正在尝试使用 C# 将文本文件的内容转换为图像,但我似乎做不到。我从System.Drawing
那里得到烦人的A generic error occurred in GDI+.
错误。
这是我的实际代码:
public static Bitmap ConvertTextToImage(string txt, string fontname, int fontsize, Color bgcolor, Color fcolor, int width, int Height)
{
Bitmap bmp = new Bitmap(width, Height);
using (Graphics graphics = Graphics.FromImage(bmp))
{
Font font = new Font(fontname, fontsize);
graphics.FillRectangle(new SolidBrush(bgcolor), 0, 0, bmp.Width, bmp.Height);
graphics.DrawString(txt, font, new SolidBrush(fcolor), 0, 0);
graphics.Flush();
font.Dispose();
graphics.Dispose();
}
bmp.Save("C:''" + Guid.NewGuid().ToString() + ".bmp");
Convert(bmp);
return bmp;
}
因此,当我尝试保存图像时,bmp.Save("C:''" + Guid.NewGuid().ToString() + ".bmp");
行会带来此错误。我阅读了帖子和类似的问题,并按照多个来源的建议将所有内容都包装在using
声明中,但我仍然缺少一些东西并且无法弄清楚。
我使用 File.ReadAllText(path);
读取文本文件的内容,然后对我的方法进行正常调用:
ConvertTextToImage(content, "Bookman Old Style", 10, Color.White, Color.Black, width, height);
因此
,您Dispose()
两次Graphics
对象。一次通过你的行说graphics.Dispose()
,一次通过using
结构自动完成。 你应该对这样写的方法没问题:
public static Bitmap ConvertTextToImage(string txt, string fontname, int fontsize, Color bgcolor, Color fcolor, int width, int Height)
{
var bmp = new Bitmap(width, Height);
using (var graphics = Graphics.FromImage(bmp))
using (var font = new Font(fontname, fontsize))
{
graphics.FillRectangle(new SolidBrush(bgcolor), 0, 0, bmp.Width, bmp.Height);
graphics.DrawString(txt, font, new SolidBrush(fcolor), 0, 0);
}
bmp.Save("C:''" + Guid.NewGuid() + ".bmp");
Convert(bmp);
return bmp;
}
由于 UAC,您会收到一般错误,因为您尝试写入 C: 驱动器的根目录,这在 Windows 中是不允许的。
更改行
bmp.Save("C:''" + Guid.NewGuid().ToString() + ".bmp");
自
bmp.Save("C:''Temp''" + Guid.NewGuid().ToString() + ".bmp");
(或您有权访问的任何其他文件夹(,允许成功创建映像。
我认为
您的应用程序无权在 C:/上编写文件。A 修改了您的代码,这对我有用:
bmp.Save(Guid.NewGuid().ToString() + ".bmp");
它会将图像保存在您的应用程序文件夹中。
此外,您不必打电话给graphics.Dispose();
,因为using
为您做这件事。