C# 圖像保存到 數據庫

        private void btnOK_Click(object sender, EventArgs e)
        {                      
            
            // 準備照片數據
            byte[] b = null;
            if (txtFilePath != "") // 文件路徑
            {
                try
                {
                    Bitmap bmp = new Bitmap(txtFilePath);  // 圖片位圖件
                    MemoryStream fs = new MemoryStream();  // 內存流
                    bmp.Save(fs, System.Drawing.Imaging.ImageFormat.Gif); // 圖像保存到內存流
                    b = new byte[fs.Length]; //  定義 內存流長度的 字節數組
                    fs.Position = 0;
                    fs.Read(b, 0, (int)fs.Length); // 內存流 讀取到 字節數組
                    fs.Close();                    

                    //FileStream fs = new FileStream(txtFilePath, FileMode.Open, FileAccess.Read);
                    //int len = Convert.ToInt32(fs.Length);
                    //b = new byte[len];
                    //fs.Read(b, 0, len);
                    //fs.Close();
                }
                catch
                {
                    b = null;
                }
            }
                         

            // 更新數據
            try
            {               
                if (txtFilePath != "" )                
                {
                    sql = "update t_user set Photo=@Photo where CID=" + ID.ToString();     
                    MySqlParameter []parm = new MySqlParameter[1];
                    parm[0] = new MySqlParameter();
                    parm[0].ParameterName = "@Photo";
                    parm[0].MySqlDbType = MySqlDbType.Binary; // 二進制數據
                    parm[0].Value = b;
                    DBHelper.ExcuteSQL(sql, parm, CommandType.Text);
                }              
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, "保存失敗", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }            
        }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章