c# Graphics 画的图形保存问题

来源:百度知道 编辑:UC知道 时间:2024/05/22 15:51:38
Bitmap bmp = new Bitmap("ss.bmp");
Graphics g= Graphics.FromImage(bmp);
Rectangle aaa = new Rectangle(0, 0, 100, 100);
g.DrawImage(bmp, 0, 0, aaa, GraphicsUnit.Pixel);
bmp.Save(strFile, System.Drawing.Imaging.ImageFormat.Bmp);

首先 这样保存是可以的吧? 但是如果这段代码要放在
OnPaint(PaintEventArgs e)
里 要让DrawImage画出图像来 就要有Graphics g = e.Graphics;
那在这样的情况下改怎么把Graphics 画的图形保存下来?
因为
Graphics g= Graphics.FromImage(bmp);
Graphics g = e.Graphics;
冲突了
有没有别的办法让Graphics 画的图形能够保存成BMP图像呢

graphics 对象有两种,
一种创建自位图
即你说的Graphics.FromImage(bmp);
一种创建自窗体
即你说的放在OnPaint里的那个e.Graphics

对于创建自窗体的graphics对象,不能直接获取它的位图,而是要先获取它所代表的窗体,然后调用窗体的DrawToBitmap方法把窗体的图像画到已有的bitmap对象里,然后再由bitmap的save方法保存
下面跳过graphics对象,直接用this获取窗体:

Bitmap b = new Bitmap(this.Width, this.Height);
this.DrawToBitmap(b, new Rectangle(0, 0, this.Width, this.Height));
b.Save("E:\\1.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);

很简单:
你需要添加一个PictureBox到窗体上,然后:
--------
Graphics g;
Bitmap bmp = new Bitmap("ss.bmp");
this.pictureBox1.Image = bmp;
g = Graphics.FromImage(this.pictureBox1.Image);
//下面你可以使用Graphics自由涂鸦,下面代码是画一个X
g.DrawLine(new Pen(Color.Red,1f),0,0,300,300);
g.DrawLine(new Pen(Color.Red,1f),0,300,300,0);

//保存涂鸦后的画
this.pictureBox1.Image.Save(strFile,System.Drawing.Imaging.ImageFormat.Bmp);
--------------
代码不用放入OnPaint方法也能实时划出来,这就