C# 用C语言在单色位图上绘制文本#

C# 用C语言在单色位图上绘制文本#,c#,.net,text,bitmap,draw,C#,.net,Text,Bitmap,Draw,我的问题是我需要在单色位图上绘制文本。生成的位图必须在热敏POS打印机上打印,因此位图必须为1bpp 我不擅长制图,所以我试着找一些样品。 以下是我尝试过的: Bitmap bmp = new Bitmap(300, 300, PixelFormat.Format1bppIndexed); using (Graphics g = Graphics.FromImage(bmp)) { Font font = new Font("Arial", 20, FontStyle.Bold, Graph

我的问题是我需要在单色位图上绘制文本。生成的位图必须在热敏POS打印机上打印,因此位图必须为1bpp

我不擅长制图,所以我试着找一些样品。 以下是我尝试过的:

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);
最后的保存只是为了检查结果。 通过这段代码,我得到了以下例外:无法从具有索引像素格式的图像创建图形对象

有没有办法将文本绘制到单色内存位图中

仅供参考:我需要这个,因为我愚蠢的POS打印机绘制的0与O的方式完全相同,所以它们无法区分…

试试这个:

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");
这里有一个链接可以帮助您:

您可以绘制普通位图,然后转换为索引格式: