保存图形内容到一个文件 [英] Saving a Graphics content to a file
问题描述
我有一些code其中我绘制函数图形成图片框
图形。在code在油漆
事件来实现。在某些时候我想保存的图形在一个文件中的内容的位图。
I have some code where I draw a function graph into a PictureBox
graphics. The code is implemented in the Paint
event. At some point I want to save a bitmap of the content of the graphics in a file.
我已经读了答案这个问题和没T找到了我一直在寻找。
I already read the answers to this question, and didn't found what I was looking for.
我需要的都在图片框绘制(或您提出任何其他控制)是为了让我不松绘图时控制隐藏什么(所以我认为我不能的createGraphics()
)的和的能够保存图形中的按钮的单击事件。
What I need is both to draw in the PictureBox (or any other control that you suggest) so that I don't loose the drawing when the control is hidden or something (so I think I cannot CreateGraphics()
) and be able to save that drawing in a button's click event.
我愿意把图纸逻辑出了油漆
事件如果necesary。
I'm willing to put the drawing logic out of the Paint
event if necesary.
先谢谢了。
推荐答案
我继续回答了基于我的假设的问题,
I went ahead and answered the question based on my assumption,
我创建了一个新的的WinForms
应用
我添加了一个面板和按钮
我创建了一个位图
名为缓存
,而在 Form1中
构造,它初始化为面板的尺寸。而不是直接绘制到面板的,我画到位图
,然后设置面板背景图片缓存
;这将增加持久性,以您的图形。如果你真的想写入一个文件,我可以告诉你这一点。只要问。
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.
要写入文件,你需要这个命名空间参考:
To write to file you will need this namespace reference :
using System.IO;
我说你问的 ImageToDisc
功能。
的这里是code:的
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:\test.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:\test.dat"));
}
这篇关于保存图形内容到一个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!