using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace WindowsApplication1
{
    public partial class Form13 : Form
    {
        public Form13()
        {
            InitializeComponent();
        }

        SqlConnection connection;
        /// <summary>
        /// 打开数据库
        /// </summary>
        private void open()
        {
            string connstring = "Data Source=(local);Initial Catalog=school;User ID=sa";
            connection = new SqlConnection(connstring);
            connection.Open();
        }
        /// <summary>
        /// 关闭数据库
        /// </summary>
        private void close()
        {
            connection.Dispose();
            connection.Close();
            connection = null;
        }
        
        /// <summary>
        /// 输入SQL命令，得到DataReader对象
        /// </summary>
        public SqlDataReader GetDataReader(string sqlstring)
        {
            open();
            SqlCommand mycom = new SqlCommand(sqlstring, connection);
            SqlDataAdapter adapter = new SqlDataAdapter();
            adapter.SelectCommand = mycom;
            SqlDataReader Dr = mycom.ExecuteReader();
            return Dr;

        }

        /// <summary>
        /*******************************************************
        **方 法  名：GetFileBytes
        **输 入参数：Filename:文件名称；
        **        
        **输 出参数：
        **返 回  值：byte[]二进制流
        **创 建  人：钱哨
        **创 建日期：08-7-9
        **描     述：将读取的文件转化成为二进制流。
        *******************************************************/
        /// <summary>
        /// </summary>
        /// <param name="Filename">打开的图片具体路径及文件名称</param>
        /// <returns>比特流类型</returns>
        public byte[] GetFileBytes(string Filename)
        {
            if (Filename == "")
                return null;
            try
            {
                FileStream fileStream = new FileStream(Filename, FileMode.Open, FileAccess.Read);
                BinaryReader binaryReader = new BinaryReader(fileStream);

                byte[] fileBytes = binaryReader.ReadBytes((int)fileStream.Length);
                binaryReader.Close();
                fileStream.Close();

                return fileBytes;
            }
            catch
            {
                return null;
            }
        }
        /// <summary>
        /// 加载并刷新当前的combobox对象控件
        /// </summary>
        private void loadcombobox()
        {
            comboBox1.Items.Clear();
            SqlDataReader dr = GetDataReader("select * from Myphoto");
            while (dr.Read())
            {
                comboBox1.Items.Add(dr[0].ToString());
            }
            close();
        }

        /// <summary>
        /// 初始化事件，加载combobox对象控件的列表信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form13_Load(object sender, EventArgs e)
        {
            loadcombobox();
        }

        /// <summary>
        /// 打开图片
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog openfile = new OpenFileDialog();
                openfile.Filter = "jpg类型图片(*.jpg)|*.jpg|BMP类型图片(*.bmp)|*.bmp";
                if (openfile.ShowDialog() == DialogResult.OK)
                {
                    byte[] picbinary = GetFileBytes(openfile.FileName);//第一步：打开图片文件，获得比特流
                    MemoryStream mempicstream = new MemoryStream(picbinary);//第二步：将比特流还存在内存工作流中。
                    pictureBox1.Image = Image.FromStream(mempicstream);//第三步：加载内存流到图片控件
                    textBox1.Text = openfile.FileName.ToString();
                    mempicstream.Dispose();
                    mempicstream.Close();
                }
            }
            catch (Exception m)
            {
                MessageBox.Show("读取图片出错，可能的问题是：" + Convert.ToString(m), "错误提示");
            }
        }
        
        

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBox1.SelectedIndex > -1)
            {
                string sqlstring = string.Format("select photo from Myphoto where pid="+comboBox1.Text);
                SqlDataReader dr = GetDataReader(sqlstring);
                if (dr.Read())
                {
                    byte[] b = (byte[])dr["photo"];
                    MemoryStream ms = new MemoryStream(b);
                    //Image img = Image.FromStream(ms);
                    Image imge = new Bitmap(ms);
                    pictureBox1.Image = imge;
                }
            }
        }
        /// <summary>
        /// 将打开的文件保存到数据库之中
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                if (pictureBox1.Image == null)
                {
                    MessageBox.Show("禁止图片为空时候存储信息。", "错误提示");
                }
                else
                {

                    MemoryStream ms = new MemoryStream();
                    Bitmap bm = new Bitmap(pictureBox1.Image);
                    bm.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                    byte[] bytes = ms.ToArray();
                    //开始向数据库写信息
                    string insert = "INSERT INTO Myphoto(Photo) VALUES (@Photo)";
                    //sql命令参数
                    open();
                    SqlCommand sqlCommand = new SqlCommand(insert, connection);
                    //此句特别重要：指定SQL操作的参数性质！
                    sqlCommand.Parameters.Add("@Photo", SqlDbType.Binary).Value = bytes;

                    sqlCommand.ExecuteNonQuery();
                    close();

                    MessageBox.Show("另存图片成功", "提示");
                                        
                    ms.Dispose();
                    ms.Close();
                    bm.Dispose();
                    loadcombobox();
                }

            }
            catch (Exception m)
            {
                MessageBox.Show("读取图片出错，可能的问题是：" + Convert.ToString(m), "错误提示");
            }
        }

        
    }
}