我接着根据我的假设回答了问题:
我创建了一个新的 winforms
应用程序
I added a panel and a button
I created a Bitmap
named buffer
, and in the Form1
constructor, initialized it to the size of the panel. Instead of drawing directly to the panel, I draw to the Bitmap
, then set the panels background image buffer
; This will add persistance to your graphics. If you truly wish to write to a file, I can show you that. Just ask.
要写入文件, 您需要此命名空间引用 :
using System.IO;
我添加了您要求的 < code> Imaage ToDisc 函数 。
这是代码:
Bitmap buffer;
public Form1()
{
InitializeComponent();
panel1.BorderStyle = BorderStyle.FixedSingle;
buffer = new Bitmap(panel1.Width,panel1.Height);
}
private void button1_Click(object sender, EventArgs e)
{
using (Graphics g = Graphics.FromImage(buffer))
{
g.DrawRectangle(Pens.Red, 100, 100,100,100);
}
panel1.BackgroundImage = buffer;
//writes the buffer Bitmap to a binary file, only neccessary if you want to save to disc
ImageToDisc();
//just to prove that it did write it to file and can be loaded I set the mainforms background image to the file
this.BackgroundImage=FileToImage();
}
//Converts the image to a byte[] and writes it to disc
public void ImageToDisc()
{
ImageConverter converter = new ImageConverter();
File.WriteAllBytes(@"c: est.dat", (byte[])converter.ConvertTo(buffer, typeof(byte[])));
}
//Converts the image from disc to an image
public Bitmap FileToImage()
{
ImageConverter converter = new ImageConverter();
return (Bitmap)converter.ConvertFrom(File.ReadAllBytes(@"c: est.dat"));
}