c# - 在 C# 中的单色位图上绘制文本

标签 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, 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 打印机绘制 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");

这是一个可以提供帮助的链接: http://msdn.microsoft.com/en-us/library/zy1a2d14.aspx

关于c# - 在 C# 中的单色位图上绘制文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18287641/

相关文章:

c# - 使用 Javascript 创建的 Cookie 无法在 C# 代码中访问....有什么原因或其他选择吗?

c# - C#中如何抓取TCP数据包

Javascript:如何从网页中检索文本

python - 大型文本数据库 : Convert to SQL or use as is

c# - 如果新约束验证失败,则 DacServices 回滚

c# - WACK 检查构建

c# - 如何更改DataGridView 中的列宽?

c# - 在 C# 中有两个散列函数的字典?

c# - Fiddler 和 .Net 3.5 SSL 错误。在 .Net 4.0 中工作正常

css - CSS 中的垂直对齐文本不起作用