如何将图形转换为位图并将其保存在c#?
目前我正在学习使用图形方法绘制条形码,并将其作为位图进行处理。但是当我要保存它时,虽然它可以成功保存,但是结果是黑色的图像,从中看不到任何东西。问题出在哪里如何将图形转换为位图并将其保存在c#?,c#,graphics,C#,Graphics,目前我正在学习使用图形方法绘制条形码,并将其作为位图进行处理。但是当我要保存它时,虽然它可以成功保存,但是结果是黑色的图像,从中看不到任何东西。问题出在哪里 private void buttonDraw_Click(object sender, EventArgs e) { System.Drawing.Graphics g = this.pictureBoxBarcode.CreateGraphics(); g.FillRectangle(ne
private void buttonDraw_Click(object sender, EventArgs e)
{
System.Drawing.Graphics g = this.pictureBoxBarcode.CreateGraphics();
g.FillRectangle(new System.Drawing.SolidBrush(System.Drawing.SystemColors.Control),
new Rectangle(0, 0, pictureBoxBarcode.Width, pictureBoxBarcode.Height));
ean13.DrawEan13Barcode(g, new System.Drawing.Point(0, 0));
g.Dispose();
}
这是我的保存功能
public void Save(Bitmap original)
{
// Displays a SaveFileDialog so the user can save the Image
// assigned to Button2.
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "JPeg Image|*.jpg|Bitmap Image|*.bmp|Gif Image|*.gif|Png Image|*.png";
saveFileDialog1.Title = "Save an Image File";
saveFileDialog1.ShowDialog();
// If the file name is not an empty string open it for saving.
if (saveFileDialog1.FileName != "")
{
// Saves the Image via a FileStream created by the OpenFile method.
System.IO.FileStream fs =
(System.IO.FileStream)saveFileDialog1.OpenFile();
// Saves the Image in the appropriate ImageFormat based upon the
// File type selected in the dialog box.
// NOTE that the FilterIndex property is one-based.
switch (saveFileDialog1.FilterIndex)
{
case 1:
original.Save(fs,
System.Drawing.Imaging.ImageFormat.Jpeg);
break;
case 2:
original.Save(fs,
System.Drawing.Imaging.ImageFormat.Bmp);
break;
case 3:
original.Save(fs,
System.Drawing.Imaging.ImageFormat.Gif);
break;
case 4:
original.Save(fs,
System.Drawing.Imaging.ImageFormat.Png);
break;
}
fs.Close();
}
}
我不能提供任何图片来证明,因为我的声誉不足以这样做。抱歉。要绘制成
位图,请使用以下代码:
private void buttonDraw_Click(object sender, EventArgs e)
{
Bitmap bmp = new Bitmap(pictureBoxBarcode.ClientSize.Width,
pictureBoxBarcode.ClientSize.Height);
using (Graphics g = Graphics.FromImage(bmp))
{
g.Clear(SystemColors.Control);
ean13.DrawEan13Barcode(g, new System.Drawing.Point(0, 0));
}
// display:
pictureBoxBarcode.Image = bmp;
// save:
bmp.Save(yourfilename, ImageFormat.Png);
// ..or..:
Save(bmp);
}
或:
我已经复制了你的绘图代码
我不知道你为什么要让它看起来灰白
我假设ean13.drawerAn13Barcode
是一个函数,它使用传入的图形
对象在与图形
对象关联的位图
上绘制一些东西。我怀疑是否有人能够在不看代码的情况下回答这个问题。看看:@SteveFerg我很好奇那个绘图区域是多少?画布、位图或其他?您有十几种不同的选择,请查看位图类定义:您有两个选项:使用PictureBox控件的Paint事件和e.Graphics对象写入PictureBox控件的表面。或者,您可以使用从位图中创建的图形对象将其绘制到位图中。-相反,你把两种方法都混用了,这是行不通的有关这两个选项的更多信息,请参见。。!对于你的答案,在看了这段代码之后,我发现我以前的错误是我用的是图形,而不是位图,对吗?灰色是什么意思?1:你的代码是混合的。请注意,您始终使用图形对象,并且它始终绑定到Btimap。如果在控件上绘制,图形对象将在绘制事件中创建,位图是控件的表面。在这里,我们绘制位图,自己创建图形对象,并可以在图像属性中显示位图2:SystemColors.Control
是一种灰色,在大多数机器上,oo,ty用于解释,我知道我错在哪里了,我只是想画一个条形码,所以我不知道SystemColors是什么。Control用于,就像在代码中一样,您已经清除了它。
private void buttonSave_Click(object sender, EventArgs e)
{
Save( (Bitmap) pictureBoxBarcode.Image);
}