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

本文关键字:绘制 文本 位图 单色 | 更新日期: 2023-09-27 18:28:11

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

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

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);

最后的Save只是为了检查结果。使用此代码,我得到以下异常:不能从具有索引像素格式的图像创建Graphics对象。

有没有任何方法可以将文本绘制到单色内存位图中?

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

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

试试这个:

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");

以下链接可能会有所帮助:http://msdn.microsoft.com/en-us/library/zy1a2d14.aspx