BMP文件写入失败
Failure in writing a BMP file
我正在尝试生成一个包含一些文本的 BMP 文件。我创建了一个 winform 应用程序,我可以成功创建 BMP(我将它显示在图片框上没有问题)。但是,当我将它保存到文件时,我得到的只是一张黑色图像。
我的密码是
private void btnNameUsage_Click(object sender, EventArgs e)
{
Bitmap bmp = new Bitmap(width, height);
string name = "Hello how are you";
string date = DateTime.Now.Date.ToString();
Graphics thegraphics = Graphics.FromImage(bmp);
string complete = date+"\n"+name ;
using (Font font1 = new Font("Arial", 24, FontStyle.Regular, GraphicsUnit.Pixel))
using (var sf = new StringFormat()
{
Alignment = StringAlignment.Center,
LineAlignment = StringAlignment.Center,
})
{
thegraphics.DrawString(complete, font1, Brushes.Black, new Rectangle(0, 0, bmp.Width, bmp.Height), sf);
}
picBoxImage.Image = bmp; //THIS WORKS
//thegraphics.Flush();//I am not sure this is necessary and it changes nothing anyway
bmp.Save(@"theImage.bmp",ImageFormat.Bmp);//I tried only one argument but it gave a png file. Now only a black BMP
}
我不知道我在这里做错了什么。感谢帮助。
PNG 有效而 BMP 无效的原因是 PNG 允许图像透明。在 BMP 中,图像的透明部分呈现为黑色(因为它必须放弃 alpha 通道)。您的文字也使用了黑色画笔,因此您将得到黑色图像。
对于屏幕呈现,这不是问题,因为那里支持透明度。
我正在尝试生成一个包含一些文本的 BMP 文件。我创建了一个 winform 应用程序,我可以成功创建 BMP(我将它显示在图片框上没有问题)。但是,当我将它保存到文件时,我得到的只是一张黑色图像。
我的密码是
private void btnNameUsage_Click(object sender, EventArgs e)
{
Bitmap bmp = new Bitmap(width, height);
string name = "Hello how are you";
string date = DateTime.Now.Date.ToString();
Graphics thegraphics = Graphics.FromImage(bmp);
string complete = date+"\n"+name ;
using (Font font1 = new Font("Arial", 24, FontStyle.Regular, GraphicsUnit.Pixel))
using (var sf = new StringFormat()
{
Alignment = StringAlignment.Center,
LineAlignment = StringAlignment.Center,
})
{
thegraphics.DrawString(complete, font1, Brushes.Black, new Rectangle(0, 0, bmp.Width, bmp.Height), sf);
}
picBoxImage.Image = bmp; //THIS WORKS
//thegraphics.Flush();//I am not sure this is necessary and it changes nothing anyway
bmp.Save(@"theImage.bmp",ImageFormat.Bmp);//I tried only one argument but it gave a png file. Now only a black BMP
}
我不知道我在这里做错了什么。感谢帮助。
PNG 有效而 BMP 无效的原因是 PNG 允许图像透明。在 BMP 中,图像的透明部分呈现为黑色(因为它必须放弃 alpha 通道)。您的文字也使用了黑色画笔,因此您将得到黑色图像。
对于屏幕呈现,这不是问题,因为那里支持透明度。