You are creating a Bitmap
object and then binding a Graphics
object to it in the using
statement. However, you then destroy that Bitmap
object and create a new one which loses that original binding. Try creating your Bitmap
only once.
EDIT
I see that you're trying to use the Graphics
object for two purposes, one to measure things and one to draw with. This isn't a bad thing but is causing your problems. I'd recommend reading the threads in this post for an alternative way for measuring strings. I'm going to use the helper class from this specific answer which I personally like the most.
public static class GraphicsHelper {
public static SizeF MeasureString(string s, Font font) {
SizeF result;
using (var image = new Bitmap(1, 1)) {
using (var g = Graphics.FromImage(image)) {
result = g.MeasureString(s, font);
}
}
return result;
}
}
string sFileData = "Hello World";
string sFileName = "Bitmap.bmp";
Font oFont = new Font("Arial", 11, FontStyle.Bold, System.Drawing.GraphicsUnit.Pixel);
var sz = GraphicsHelper.MeasureString(sFileData, oFont);
var oBitmap = new Bitmap((int)sz.Width, (int)sz.Height);
using (Graphics oGraphics = Graphics.FromImage(oBitmap)) {
oGraphics.Clear(Color.White);
oGraphics.DrawString(sFileData, oFont, new SolidBrush(System.Drawing.Color.Black), 0, 0);
oGraphics.Flush();
}
oBitmap.Save(sFileName, System.Drawing.Imaging.ImageFormat.Bmp);