???????? 这几天突然对文件流操作产生了兴趣,闲暇时间做了一个数据流操作的一种应用实例!发出来供大家参考(这篇博文对于俺来说还是大姑娘上轿头一回呐,呵呵...)。
?
??????? 先是将图片上传保存到数据库中,代码如下:
??????? private void btnSave_Click(object sender,EventArgs e) ??????? { ??????????? OpenFileDialog ofd = new OpenFileDialog();//创建一个文件选择对话框 ??????????? ofd.InitialDirectory = "C://Users//Public//Pictures//Sample Pictures";//设置对话框内容所显示的位置 ??????????? ofd.Filter = "All files (*.*)|*.*|files (*.jpg,*.png)|*.jpg;*.png";//设置对话框中的筛选框内容 ??????????? ofd.FilterIndex = 2;//设置筛选框的索引项 ??????????? ofd.RestoreDirectory = true;//关闭对话框时,还原对话框索引目录 ??????????? if (ofd.ShowDialog() == DialogResult.OK)//判断用户是否点击确定 ??????????? { ??????????????? String fileURL = ofd.FileName;//获取文件目录 ??????????????? FileStream fs = new FileStream(fileURL,FileMode.Open,FileAccess.Read);//创建一个文件流对象 ??????????????? byte[] ib = new byte[fs.Length];//创建一个btye类型的数组用以保存二级制数据 ??????????????? fs.Read(ib,Convert.ToInt32(fs.Length));//将图片以二进制保存到ib里 ??????????????? DBTool DBT = new DBTool(); ??????????????? String id = Guid.NewGuid().ToString(); ??????????????? string cmdText = "INSERT INTO [TestImage] VALUES(@id,@img)"; ??????????????? SqlParameter[] ss = new SqlParameter[]{ ??????????????????? new SqlParameter("@id",id), ??????????????????? new SqlParameter("@img",SqlDbType.Image,(int)fs.Length)//这里的写法需要注意 ??????????????? }; ??????????????? ss[1].Value = ib; ??????????????? int i = DBT.ExecuteNonQuery(cmdText,CommandType.Text,ss); ??????????????? if (i > 0) ??????????????? { ??????????????????? MessageBox.Show("图片保存成功!"); ??????????????? } ??????????? } ??????? }
?
??????? 之后就是将保存到数据库中的二进制数据还原成图片,代码如下:
????????private void btnPicShow_Click(object sender,EventArgs e) ??????? { ??????????? DBTool DBT = new DBTool(); ??????????? string cmdText = "SELECT TOP 1 * FROM [TestImage]"; ??????????? DataTable dt = DBT.ExecuteQuery(cmdText,null);
??????????? byte[] _ImageByte = (byte[])dt.Rows[0]["img"];//个人认为使用DataTable比用SqlDataReader好:
??????????? 因为使用SqlDataReader时不能在数据访问层将数据库连接给关闭,会破坏了分层的结构。 ??????????? System.IO.MemoryStream _ImageMem = new System.IO.MemoryStream(_ImageByte); ??????????? Image _Image = Image.FromStream(_ImageMem); ??????????? pictureBox1.Image = _Image; ??????? }
???????? 以上就是实现关键部分的代码了,如有哪里方式实现不好欢迎大家给我发帖!
(编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|