Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drawing Text on monochrome Bitmap in C#

My problem is that I need to draw text on a monochrome bitmap. The resulting bitmap has to be printed on a thermal POS printer, so the bitmap has to be 1bpp.

I'm not good in graphics, so I've tried to find some samples. Here's what I've tried:

Bitmap bmp = new Bitmap(300, 300, PixelFormat.Format1bppIndexed);
using (Graphics g = Graphics.FromImage(bmp))
{
  Font font = new Font("Arial", 20, FontStyle.Bold, GraphicsUnit.Point);
  g.Clear(Color.White);
  g.DrawString(text, font, Brushes.Black, 0, 0);
}
bmp.Save(@"c:\x\x.bmp", ImageFormat.Bmp);

the Save at the end was just to check the result. With this code, I get the following exception: A Graphics object cannot be created from an image that has an indexed pixel format.

Is there ANY way to draw text to a monochrome memory bitmap?

Just for info: I need this because my stupid POS Printer draws a 0 exactly the same way as a O, so they're impossible to distinguish...

like image 777
AlexK Avatar asked Aug 17 '13 10:08

AlexK


1 Answers

Try this:

Bitmap bmp = new Bitmap(300, 300);
        using (Graphics g = Graphics.FromImage(bmp))
        {
            Font font = new Font("Arial", 20, FontStyle.Bold, GraphicsUnit.Point);
            g.Clear(Color.White);
            g.DrawString("Hello", font, Brushes.Black, 0, 0);
        }
        System.Drawing.Imaging.BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format1bppIndexed);
        Bitmap newBitmap = new Bitmap(300, 300, bmpData.Stride, System.Drawing.Imaging.PixelFormat.Format1bppIndexed, bmpData.Scan0);
        newBitmap.Save(@"c:\x\x.bmp");

Here is a link that could help: http://msdn.microsoft.com/en-us/library/zy1a2d14.aspx

like image 133
Hadron Avatar answered Nov 16 '22 09:11

Hadron