[英]How to convert Graphics to bitmap and save it in c#?
目前我正在學習使用圖形方法繪制條形碼並將其處理為位圖。 但是當我要保存它時,雖然可以保存成功,但結果是黑色圖像,從那里看不到任何東西。 發生了什么問題?
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();
}
}
我無法提供任何圖片來證明我的聲譽還不夠。 對不起。
要繪制Bitmap
使用以下代碼:
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);
}
或者:
private void buttonSave_Click(object sender, EventArgs e)
{
Save( (Bitmap) pictureBoxBarcode.Image);
}
我已經復制了你的繪圖代碼。
我不知道你為什么想讓它看起來是灰色的..?
我假設ean13.DrawEan13Barcode
是一個函數,它使用傳入的Graphics
對象在與Graphics
對象關聯的Bitmap
上繪制一些東西。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.