Brian Schamel
Brian Schamel

Reputation: 29

Drawing text on a bitmap - image comes out black

I'm trying to draw text onto a bitmap, and the image is coming out black.

protected Bitmap DrawTextImage(string text, float fontsize, string fontname = "Helvetica")
{
    string imagePath = @"C:\img.bmp";
    string imagePathTest = @"C:\imgTest.bmp";
    Font textFont = new Font(fontname, fontsize);
    var size = TextRenderer.MeasureText(text, textFont);
    Bitmap bmp = new Bitmap(size.Width, size.Height);

    Graphics graphics = Graphics.FromImage(bmp);
    SolidBrush brush = new SolidBrush(Color.Black);
    graphics.DrawString(text, textFont, brush, size.Width, size.Height);
    if(File.Exists(imagePathTest))
        File.Delete(imagePathTest);
    bmp.Save(imagePathTest, ImageFormat.Bmp);

For what it's worth, the image also needs to be eventually converted into a bitmap format for printing on a thermal printer, but I'm just focused on this part for the moment.

The arguments i'm using here are DrawTextImage(text, 36);

Upvotes: 0

Views: 922

Answers (1)

user585968
user585968

Reputation:

I'm trying to draw text onto a bitmap, and the image is coming out black.

The resulting image is black because you are drawing in black...on a black background. The reason for the black background is that bitmaps default to black.

You just need to call FillRectangle (or Clear() as mentioned in the comments) to a different color just after obtaining graphics prior to any other drawing.

Change:

Graphics graphics = Graphics.FromImage(bmp);
SolidBrush brush = new SolidBrush(Color.Black);
graphics.DrawString(text, textFont, ...);

...to:

Graphics graphics = Graphics.FromImage(bmp);
graphics.FillRectangle (Brushes.White, 0, 0, size.Width, size.Height); // Fill to white
SolidBrush brush = new SolidBrush(Color.Black);
graphics.DrawString(text, textFont, ...);

For a simpler approach, try graphics.Clear(Color.White).

Tips

1. Dispose GDI Objects When Done

Because you're creating an explicit Graphics and Brush that isn't used anywhere else, it's a good idea to Dispose them when you are finished. GDI resources have always been a system-wide limited resource on Windows, irrespective of bitness and installed RAM.

e.g.

using (var graphics = Graphics.FromImage(bmp))
{
...
    graphics.DrawString(text, ...);
    if(File.Exists(imagePathTest))
        File.Delete(imagePathTest);
    bmp.Save(imagePathTest, ImageFormat.Bmp);
...
}

2. Use Pre-defined GDI Brushes/Pens Where Possible

Instead of creating brushes, try to use one of the pre-existing brushes or pens. They're quicker to obtain; don't need disposing because they're system-wide.

Instead of:

var brush = new SolidBrush(Color.Black);

...use:

_blackBrush = Brushes.Black; // optionally save in a field for future use

Upvotes: 2

Related Questions