【问题标题】:Drawing text on a bitmap - image comes out black在位图上绘制文本 - 图像变黑
【发布时间】:2020-02-03 21:33:27
【问题描述】:

我正在尝试在位图上绘制文本,但图像变黑了。

protected Bitmap DrawTextImage(string text, float fontsize, string fontname = "Helvetica")
{
    string imagePath = @"C:\img.bmp";
    string imagePathTest = @"C:\imgTest.bmp";
    Font textFont = new Font(fontname, fontsize);
    var size = TextRenderer.MeasureText(text, textFont);
    Bitmap bmp = new Bitmap(size.Width, size.Height);

    Graphics graphics = Graphics.FromImage(bmp);
    SolidBrush brush = new SolidBrush(Color.Black);
    graphics.DrawString(text, textFont, brush, size.Width, size.Height);
    if(File.Exists(imagePathTest))
        File.Delete(imagePathTest);
    bmp.Save(imagePathTest, ImageFormat.Bmp);

对于它的价值,图像最终还需要转换为位图格式,以便在热敏打印机上打印,但我暂时只关注这部分。

我在这里使用的参数是DrawTextImage(text, 36);

【问题讨论】:

  • @maccettura graphics.DrawString() 将修改底层图像
  • @maccettura 。 Graphics 对象不包含任何图形;它是一个工具,可让您绘制到相关位图上,包括控件的表面。 - 不过,它应该在using 子句中创建。
  • 您正在用黑色画笔在黑色位图旁边绘制。
  • 您仍在位图右侧绘制。在 (0,0) 处绘制!
  • 它已经是已发布答案的一部分。只要语言警察在巡逻,我就不再在这里发布答案了。

标签: c# image-processing bitmap


【解决方案1】:

我正在尝试在位图上绘制文本,但图像变黑了。

生成的图像是黑色的,因为您在黑色背景上绘制...在黑色背景上。黑色背景的原因是位图默认为黑色。

您只需在获得graphics 之后,在任何其他绘图之前调用FillRectangle(或cmets 中提到的Clear())为不同的颜色。

变化:

Graphics graphics = Graphics.FromImage(bmp);
SolidBrush brush = new SolidBrush(Color.Black);
graphics.DrawString(text, textFont, ...);

...到:

Graphics graphics = Graphics.FromImage(bmp);
graphics.FillRectangle (Brushes.White, 0, 0, size.Width, size.Height); // Fill to white
SolidBrush brush = new SolidBrush(Color.Black);
graphics.DrawString(text, textFont, ...);

如需更简单的方法,请尝试graphics.Clear(Color.White)

提示

1.完成后处理 GDI 对象

因为您正在创建一个明确的GraphicsBrush,它不会在其他任何地方使用,所以最好在完成后Dispose 它们。 GDI 资源在 Windows 上一直是系统范围的有限资源,与位数和安装的 RAM 无关。

例如

using (var graphics = Graphics.FromImage(bmp))
{
...
    graphics.DrawString(text, ...);
    if(File.Exists(imagePathTest))
        File.Delete(imagePathTest);
    bmp.Save(imagePathTest, ImageFormat.Bmp);
...
}

2。尽可能使用预定义的 GDI 画笔/笔

不要创建画笔,而是尝试使用现有的画笔或钢笔之一。它们可以更快地获得;不需要处理,因为它们是系统范围的。

代替:

var brush = new SolidBrush(Color.Black);

...使用:

_blackBrush = Brushes.Black; // optionally save in a field for future use

【讨论】:

  • graphics.Clear(Color.White); 也可以工作,graphics.DrawString 可能应该在位置 0 绘制,即 `graphics.DrawString(text, textFont, Brush, 0, 0);'
  • 他还应该避免泄漏资源,比如图形对象和画笔..
  • @MickyD 我尝试了你的建议,但现在我得到的是纯白色图像而不是纯黑色。但是,看起来打印机本身在打印之前会反转颜色(所以我发送的这个纯白色图像实际上是纯黑色)。我正在更新我的帖子以提供更多信息。
  • @BrianSchamel 这听起来像是一个新问题。随意张贴
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-07
  • 1970-01-01
  • 2019-07-25
  • 1970-01-01
  • 2023-03-07
相关资源
最近更新 更多