winform 导入导出图片

本文介绍了一个使用C#进行图片文件的操作方法,包括从文件系统读取图片并显示在PictureBox中,将图片文件转化为二进制数据存入SQL Server数据库,以及从数据库中读取图片数据并再次显示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog op = new OpenFileDialog();
            if (op.ShowDialog()==DialogResult.OK)
            {
                FileStream fs = new FileStream(op.FileName,FileMode.Open);
                Image img = System.Drawing.Bitmap.FromStream(fs);
                pictureBox1.Image = img;
                fs.Close();
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            OpenFileDialog op = new OpenFileDialog();
            if (op.ShowDialog() == DialogResult.OK)
            {
                FileStream fs = new FileStream(op.FileName, FileMode.Open);
                BinaryReader dr = new BinaryReader(fs);
                byte[] by=new byte[fs.Length];
               by= dr.ReadBytes((int)fs.Length);
               SqlConnection conn = new SqlConnection("server=.;database=students_information;user=sa;pwd=123");
               conn.Open();
               SqlCommand cmd = conn.CreateCommand();
               cmd.CommandText = "insert into img(img) values(@img)";
               cmd.Parameters.Add(new SqlParameter("@img",by));
               cmd.ExecuteNonQuery();
               cmd.Dispose();
               conn.Close();
               MessageBox.Show("添加成功");
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            byte[] by = null;
            SqlConnection conn = new SqlConnection("server=.;database=students_information;user=sa;pwd=123");
            conn.Open();
            SqlCommand cmd = conn.CreateCommand();
            cmd.CommandText = "select * from img";
            SqlDataReader dr = cmd.ExecuteReader();
            if (dr.Read())
            {
                by = (byte[])dr["img"];
            }
           
            conn.Close();

            MemoryStream ms = new MemoryStream(by);
            Image img = System.Drawing.Bitmap.FromStream(ms);
            pictureBox1.Image = img;
            ms.Close();

        }

 

转载于:https://www.cnblogs.com/lushixiong/p/4561159.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值