gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 21:22:47 24 4
gpt4 key购买 nike

我的问题是我需要在单色位图上绘制文本。生成的位图必须在热敏 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com