winform GDI 画图并保存图片
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace GDITest
{
public partial class Form1 : Form
{
Bitmap bmp;
public Form1()
{
InitializeComponent();
}
private void menuSaveImage_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "JPeg Image|*.jpg|Png Image|*.png|Bitmap Image|*.bmp|Gif Image|*.gif";
saveFileDialog1.Title = "图片另存为";
saveFileDialog1.ShowDialog();
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:
this.pic.Image.Save(fs,
System.Drawing.Imaging.ImageFormat.Jpeg);
break;
case 2:
this.pic.Image.Save(fs,
System.Drawing.Imaging.ImageFormat.Png);
break;
case 3:
this.pic.Image.Save(fs,
System.Drawing.Imaging.ImageFormat.Bmp);
break;
case 4:
this.pic.Image.Save(fs,
System.Drawing.Imaging.ImageFormat.Gif);
break;
}
fs.Close();
MessageBox.Show("保存完毕!");
}
}
private void Form1_Load(object sender, EventArgs e)
{
//Graphics g = this.pic.CreateGraphics();
//g.Clear(this.pic.BackColor);
// 892*644
bmp = new Bitmap(pic.Width, pic.Height);
Graphics g = Graphics.FromImage(bmp);
g.Clear(Color.White);
Pen pen = new Pen(Color.Black, 2);
pen.StartCap = System.Drawing.Drawing2D.LineCap.Round;
g.DrawLine(pen, 0, 0, 0, 644);
g.DrawRectangle(Pens.Black, pic.Width / 2 - 10, 0, 100, 30);
g.DrawString("GDI Test", new Font("宋体", 12), Brushes.Black, new PointF(pic.Width/2, 5));
g.DrawEllipse(pen, pic.Width / 2, pic.Height / 2, 30, 30);
// pic为picturebox图片控件
pic.Image = bmp;
}
}
}