I am trying to convert the contents of a text file to an image using C#, but I cannot seem to do it. I get the annoying A generic error occurred in GDI+.
error from System.Drawing
.
Here is my actual code:
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;
}
So at the line bmp.Save("C:\\" + Guid.NewGuid().ToString() + ".bmp");
when I try to save the image, it brings this error. I read posts and similar questions and wrapped everything around a using
statement as suggested at multiple sources, but I am still missing something and cannot figure it out.
I use the File.ReadAllText(path);
to read the contents of the text file and then I make a normal call to my method:
ConvertTextToImage(content, "Bookman Old Style", 10, Color.White, Color.Black, width, height);
Due to UAC, your are getting the generic error because you are trying to write to the root directory of the C: drive, which is not allowed in Windows.
Changing the line
bmp.Save("C:\\" + Guid.NewGuid().ToString() + ".bmp");
to
bmp.Save("C:\\Temp\\" + Guid.NewGuid().ToString() + ".bmp");
(or any other folder that you have permissions for), allows the successful creation of the image.