码迷,mamicode.com
首页 > Windows程序 > 详细

Winform 存取图片

时间:2015-11-11 19:15:25      阅读:288      评论:0      收藏:0      [点我收藏+]

标签:

namespace WindowsFormsApplication10
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            openFileDialog1.Filter = "@.Jpg|*.jpg|@.Gif|*.gif|@.Png|*.png|All files|*.*";
            DialogResult dr = openFileDialog1.ShowDialog();

            if (dr == DialogResult.OK)
            {
                //将图片读入到文件流
                FileStream fs = new FileStream(openFileDialog1.FileName,FileMode.Open,FileAccess.Read);
                Image img = System.Drawing.Bitmap.FromStream(fs);//绘制
                pictureBox1.Image = img;//指定
              
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            openFileDialog1.Filter = "@.Jpg|*.jpg|@.Gif|*.gif|@.Png|*.png|All files|*.*";
            DialogResult dr = openFileDialog1.ShowDialog();
            if (dr == DialogResult.OK)
            {
                //文件流
                FileStream fs = new FileStream(openFileDialog1.FileName,FileMode.Open,FileAccess.Read);
                BinaryReader br = new BinaryReader(fs);//二进制读取器
                byte[] buffer =  br.ReadBytes(int.Parse(fs.Length.ToString()));

                //连接数据库
                SqlConnection conn = new SqlConnection("server=.;database=snewData;user=sa;pwd=");
                SqlCommand cmd = conn.CreateCommand();
                cmd.CommandText = "insert into imgtable values(@buffer)";
                cmd.Parameters.Add("@buffer",buffer);
                conn.Open();
                cmd.ExecuteNonQuery();
                cmd.Dispose();
                conn.Close();
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            //读取数据库
            SqlConnection conn = new SqlConnection("server=.;database=snewData;user=sa;pwd=");
            SqlCommand cmd = conn.CreateCommand();
            cmd.CommandText = "select *from imgtable where code=4";
            conn.Open();
            SqlDataReader dr = cmd.ExecuteReader();
            dr.Read();
            byte[] buffer = (byte[])dr["imgs"];
            
            cmd.Dispose();
            conn.Close();
            //将二进制数据buffer显示为图片
            MemoryStream ms = new MemoryStream(buffer);//构建对象
            ms.Write(buffer,0,buffer.Length);//写到内存流中
            Image img = System.Drawing.Image.FromStream(ms);
            pictureBox1.Image = img;

        }
    }
}

  

Winform 存取图片

标签:

原文地址:http://www.cnblogs.com/ROCKyou/p/4956790.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!