【问题标题】:Creating Bitmap and saving to File in C# gives me an empty Text on Bitmap在 C# 中创建位图并保存到文件在位图上给了我一个空文本
【发布时间】:2014-02-12 20:10:39
【问题描述】:

我有以下代码,它接受一个字符串并将其添加到内存中的位图,然后将其保存为 BMP 文件。我目前的代码如下;

string sFileData = "Hello World";
string sFileName = "Bitmap.bmp";

Bitmap oBitmap = new Bitmap(1,1);
Font oFont = new Font("Arial", 11, FontStyle.Bold, System.Drawing.GraphicsUnit.Pixel);
int iWidth = 0;
int iHeight = 0;

using (Graphics oGraphics = Graphics.FromImage(oBitmap))
{
    oGraphics.Clear(Color.White);

    iWidth = (int)oGraphics.MeasureString(sFileData, oFont).Width;
    iHeight = (int)oGraphics.MeasureString(sFileData, oFont).Height;
    oBitmap = new Bitmap(oBitmap, new Size(iWidth, iHeight));

    oGraphics.DrawString(sFileData, oFont, new SolidBrush(System.Drawing.Color.Black), 0, 0);

    oGraphics.Flush();

}

oBitmap.Save(sFileName, System.Drawing.Imaging.ImageFormat.Bmp);

我遇到的问题是当我在Paint中查看BMP文件时,位图的大小定义正确,背景是白色的,但是它们没有文字?

我做错了什么?

【问题讨论】:

    标签: c# bitmap image-manipulation


    【解决方案1】:

    您正在创建一个Bitmap 对象,然后在using 语句中将一个Graphics 对象绑定到它。但是,您随后会销毁该 Bitmap 对象并创建一个新的对象,该对象会丢失该原始绑定。尝试只创建一次Bitmap

    编辑

    我看到您正在尝试将Graphics 对象用于两个目的,一个用于测量事物,一个用于绘图。这不是一件坏事,但会导致您的问题。我推荐reading the threads in this post for an alternative way for measuring strings。我将使用我个人最喜欢的helper class from this specific answer

    public static class GraphicsHelper {
        public static SizeF MeasureString(string s, Font font) {
            SizeF result;
            using (var image = new Bitmap(1, 1)) {
                using (var g = Graphics.FromImage(image)) {
                    result = g.MeasureString(s, font);
                }
            }
         return result;
        }
    }
    
    string sFileData = "Hello World";
    string sFileName = "Bitmap.bmp";
    
    Font oFont = new Font("Arial", 11, FontStyle.Bold, System.Drawing.GraphicsUnit.Pixel);
    var sz = GraphicsHelper.MeasureString(sFileData, oFont);
    
    var oBitmap = new Bitmap((int)sz.Width, (int)sz.Height);
    
    using (Graphics oGraphics = Graphics.FromImage(oBitmap)) {
        oGraphics.Clear(Color.White);
        oGraphics.DrawString(sFileData, oFont, new SolidBrush(System.Drawing.Color.Black), 0, 0);
        oGraphics.Flush();
    
    }
    
    oBitmap.Save(sFileName, System.Drawing.Imaging.ImageFormat.Bmp);
    

    【讨论】:

    • +1 用于发现问题,但是您的示例将不起作用,因为您在定义之前使用 oGraphics
    【解决方案2】:

    您似乎正在中途交换位图。您似乎正在执行以下操作:

    1. 创建位图
    2. 获取位图的图形句柄
    3. 创建一个不同大小的新位图

    问题是您仍在使用与旧(第一个)位图相关联的图形句柄(来自第 2 步),而不是新的(第二个)位图。

    您需要使用与新(第二个)位图关联的图形句柄,而不是旧(第一个)位图。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-23
      • 2017-08-19
      • 1970-01-01
      • 1970-01-01
      • 2013-03-16
      • 1970-01-01
      • 2011-05-08
      相关资源
      最近更新 更多