c# winform下sql圖片二進位制儲存/讀取/顯示/寫入XML/讀取XML顯示

iDotNetSpace發表於2009-11-16
winform下:
        //儲存

        private void MemoryImage()
        {
            string sql = "";
            //string conn = "Provider=SQLNCLI;Data Source=192.168.0.9,1433;Database=WebDown;UID=sa;PWD=111122;";

            Stream ms;
            byte[] picbyte;
            OpenFileDialog fdSelectPic = new OpenFileDialog();
            if (ofdSelectPic.ShowDialog() == DialogResult.OK)
            {
                if ((ms = ofdSelectPic.OpenFile()) != null)
                {
                    picbyte = new byte[ms.Length];
                    ms.Position = 0;
                    ms.Read(picbyte, 0, Convert.ToInt32(ms.Length));

                    //連線資料庫
                    SqlConnection conn = new SqlConnection();
                    conn.ConnectionString = "Data Source=192.168.0.9,1433;Database=WebDown;UID=sa;PWD=111122;";

                    sql = "Insert into LibraryCover(Cover) values(@UpdateImage)";
                    SqlCommand cmd = new SqlCommand(sql, conn);

                    cmd.Parameters.Add("@UpdateImage", SqlDbType.VarBinary);
                    cmd.Parameters["@UpdateImage"].Value = picbyte;

                    conn.Open();
                    cmd.ExecuteNonQuery();
                    conn.Close();

                    ms.Close();
                }
            }

            MessageBox.Show("完成!");
        }
        //讀取

        private void ShowImage()
        {
            string sql = "";
            sql = "select Cover from LibraryCover where LibID=1";
            SqlConnection conn = new SqlConnection();
            conn.ConnectionString = "Data Source=192.168.0.9,1433;Database=WebDown;UID=sa;PWD=111122;";
            SqlCommand cmd = new SqlCommand(sql,conn);
            conn.Open();
            SqlDataReader reader = cmd.ExecuteReader();
            reader.Read();
            MemoryStream ms = new MemoryStream((byte[])reader["Cover"]);
            Image image = Image.FromStream(ms, true);

            reader.Close();
            conn.Close();
            pictureBox1.Image = image;
        }

        //批量儲存

        private void button12_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog FBD = new FolderBrowserDialog();
            FBD.ShowDialog();
            DBImages(FBD.SelectedPath);
        }
        ///


        /// 圖片二進位制存SQL庫
        ///

        /// 圖片所在資料夾
        private void DBImages(string path)
        {
            Stream ms;
            string sql = "";
            byte[] picbyte;
            string FolderName = "";
            string[] Folders;
            string connStr = "Data Source=192.168.0.9,1433;Database=WebDown;UID=sa;PWD=111122;";
            SqlConnection conn = new SqlConnection(connStr);
            Folders = Directory.GetFiles(path);
            foreach (string folder in Folders)
            {
                if ((ms = File.OpenRead(folder))!= null)
                {
                    picbyte = new byte[ms.Length];
                    ms.Position = 0;
                    ms.Read(picbyte, 0, Convert.ToInt32(ms.Length));

                    sql = "insert into LibraryCover(ImageName,Cover) values(@ImageName,@Cover)";
                    SqlCommand cmd = new SqlCommand(sql, conn);

                    cmd.CommandType = CommandType.Text;
                    FolderName = Path.GetFileNameWithoutExtension(folder);
                    cmd.Parameters.Add("@ImageName", SqlDbType.VarChar, 255).Value = FolderName;
                    cmd.Parameters.Add("@Cover", SqlDbType.VarBinary).Value = picbyte;

                    conn.Open();
                    cmd.ExecuteNonQuery();
                    conn.Close();
                    ms.Close();
                }
            }
            MessageBox.Show("儲存完成!");
        }

        //批量讀取

        private void button13_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog FBD = new FolderBrowserDialog();
            FBD.ShowDialog();
            getImageShow(FBD.SelectedPath);
        }
        ///


        /// sql庫二進位制圖片顯示在儲存器上
        ///

        /// 要儲存圖片的位置
        private void getImageShow(string path)
        {
            string sql = "";
            string conn = "Data Source=192.168.0.9,1433;Database=WebDown;UID=sa;PWD=111122;";
            sql = "select ImageName,Cover from LibraryCover order by LibID";
            SqlDataReader sdr = GetList(conn,sql);
            while (sdr.Read())
            {
                byte[] bytes = (byte[])sdr["Cover"];
                FileStream fs = new FileStream(path+@"\" + sdr["ImageName"] + ".jpg", FileMode.Create, FileAccess.Write);
                fs.Write(bytes, 0, bytes.Length);
                fs.Flush();
                fs.Close();
            }
            MessageBox.Show("完成!");
        }
        public SqlDataReader GetList(string conn, string Sql)
        {
            SqlConnection myConnection = new SqlConnection(conn);
            SqlCommand myCommand = new SqlCommand(Sql, myConnection);

            myConnection.Open();
            SqlDataReader result = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
            return result;
        }

        private void getImage()
        {
            int num = 0;
            string path = @"D:\bookpic";
            Stream ms;
            string sql = "";
            byte[] picbyte;
            FileInfo[] Folders;
            string[] files;
            string FilePath = "";
            string connStr = "Data Source=192.168.0.200,1433;Database=MISTemp;UID=sa;PWD=111122;";
            SqlConnection conn = new SqlConnection(connStr);
            DirectoryInfo DI = new DirectoryInfo(path);
            Folders = DI.GetFiles("*.*",SearchOption.AllDirectories);
            foreach (FileInfo file in Folders)
            {
                num++;
                txt_num.Text = num.ToString();
                FilePath = file.FullName.Replace(@"D:\", "").Replace(@"\","/");
                if ((ms = File.OpenRead(file.FullName)) != null)
                {
                    picbyte = new byte[ms.Length];
                    ms.Position = 0;
                    ms.Read(picbyte, 0, Convert.ToInt32(ms.Length));

                    sql = "update shop_books set Cover=@Cover where bookpic='" + modsql(FilePath) + "'";
                    SqlCommand cmd = new SqlCommand(sql, conn);

                    cmd.CommandType = CommandType.Text;
                    cmd.CommandTimeout = 10000;
                    cmd.Parameters.Add("@Cover", SqlDbType.VarBinary).Value = picbyte;

                    conn.Open();
                    cmd.ExecuteNonQuery();
                    conn.Close();
                    ms.Close();
                }
            }
           
            MessageBox.Show("儲存完成!");
        }
        public string modsql(string sql)
        {
            return sql.Replace("'", "''");
        }

//Image寫入XML
using System.IO;
using System.Runtime.Serialization.Formatters.Soap;

        string MyFile = @"D:\資料處理\image.xml";
        string imageFile = @"G:\zengwei.jpg";
        Stream MyStream;
        SoapFormatter MyFormatter =new SoapFormatter();
        

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                MyStream = new FileStream(MyFile, FileMode.Create, FileAccess.Write, FileShare.None);
                MyFormatter.Serialize(MyStream, pictureBox1.Image);
                MyStream.Close();
                MessageBox.Show("完成!");
            }
            catch (Exception ex)
            {
               
            }
        }
//讀取XML顯示IMAGE
        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                MyStream = new FileStream(MyFile, FileMode.Open, FileAccess.Read, FileShare.None);
                pictureBox1.Image = (Bitmap)MyFormatter.Deserialize(MyStream);
                MyStream.Close();
            }
            catch (Exception ex)
            { }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            pictureBox1.Image = Image.FromFile(imageFile);
        }

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/12639172/viewspace-619710/,如需轉載,請註明出處,否則將追究法律責任。

相關文章