C#语言___图片__增删改查操作

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.IO;//图片操作时using指令

namespace TuPian_Operate
{                                         //在定义数据库中的字段时:字段image 类型image、varbinary(MAX)
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        public int XiuGaiTuPianFou = 0;
        public string filePath;//文件的路径
        public byte[] content;//文件的内容(图片转化为二进制)
        public byte[] TuPian;//存储图片


        #region 从文件夹中获取图片
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog myOpenFileDialog = new OpenFileDialog();
                myOpenFileDialog.Filter = "*.bmp;*.jpg;*.gif|*.bmp;*.jpg;*.gif;*.jpeg";
                myOpenFileDialog.ShowDialog();
                filePath = myOpenFileDialog.FileName;
                this.pictureBox1.Image = Image.FromFile(filePath);
                XiuGaiTuPianFou = 1;
            }
            catch
            {

            }
        } 
        #endregion

        #region 将图片保存到数据库中
        private void button2_Click(object sender, EventArgs e)
        {
            //保存图片
            if (XiuGaiTuPianFou == 1)
            {
                FileInfo finfo = new FileInfo(filePath);
                if (finfo.Exists)
                {
                    content = new byte[finfo.Length];
                    FileStream stream = finfo.OpenRead();
                    stream.Read(content, 0, content.Length);
                    stream.Close();
                }
                TuPian = content;//获取图片,然后将TuPian作为参数传入数据库
                XiuGaiTuPianFou = 0;
            }
        } 
        #endregion

        #region 从数据库中提取并将图片显示出来
        private void button3_Click(object sender, EventArgs e)
        {
            DataTable myDataTable = new DataTable();
            
            //提取某个员工的信息,绑定到datatable
            //myDataTable = BLL_RenLiZiYuan.ZhaoPinGuanLi_ZengJiaYuanGong.SelectYuanGongXinXi(myXiTong_YuanGongXinXi);

            //将二进制的图片读取出来
            if (myDataTable.Rows[0]["TuPian"].ToString() != "")
            {
                MemoryStream myMemoryStream = new MemoryStream((Byte[])(myDataTable.Rows[0]["TuPian"]));
                pictureBox1.Image = Image.FromStream(myMemoryStream);
            }

        } 
        #endregion
    }
}

 

posted on 2013-10-16 21:47  AllEn—Carina  阅读(433)  评论(0编辑  收藏  举报