c# winform下sql图片二进制存储/读取/显示/写入XML/读取XML

c# winform下sql图片二进制存储/读取/显示/写入XML/读取XML

//存储

        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);
        }
        /// <summary>
        /// 图片二进制存SQL库
        /// </summary>
        /// <param name="path">图片所在文件夹</param>
        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);
        }
        /// <summary>
        /// sql库二进制图片显示在存储器上
        /// </summary>
        /// <param name="path">要存储图片的位置</param>
        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);
        }




///////////////////////////////////////////////////////////

.net教程:winform直接显示二进制数据中的图片

//读取DataSet中以二进制(Image)形式保存的图片
            byte[] byteImage = (byte[])dataSet11.tBGPicture.Rows[2]["PicContent"];

            //转成MemoryStream类型
            System.IO.MemoryStream stream = new System.IO.MemoryStream(byteImage, true);
            //stream.Write(byteImage, 0, byteImage.Length); 

            //显示图片
            pictureBox1.Image = Image.FromStream(stream);   
            
            //关闭stream
            stream.Close();

nathanma

leave a comment

Create Account



Log In Your Account