在C#中的单色位图上绘制文本 [英] Drawing Text on monochrome Bitmap in C#

查看:310
本文介绍了在C#中的单色位图上绘制文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

最后的保存只是检查结果. 使用此代码,我得到以下异常:无法从具有索引像素格式的图像中创建Graphics对象.

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?

仅供参考:我需要这样做,因为我的愚蠢POS打印机绘制0的方式与O完全相同,因此无法区分...

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...

推荐答案

尝试一下:

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

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

这篇关于在C#中的单色位图上绘制文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆