=
Image.FromStream(this.openFileDialog1.OpenFile())
//获取当前图片的路径
string
path
=
openFileDialog1.FileName.ToString()
//将制定路径的图片添加到FileStream类中
FileStream
fs
=
new
FileStream(path,
FileMode.Open,
FileAccess.Read)
//通过FileStream对象实例化BinaryReader对象
BinaryReader
br
=
new
BinaryReader(fs)
//通过BinaryReader类对象的ReadBytes()方法将FileStream类对象转化为二进制数组
byte[]
imgBytesIn
=
br.ReadBytes(Convert.ToInt32(fs.Length))第二步:
//将图片添加到数据库中
string
sql="insert
into
pic
values(@pic)"
SqlParameter[]
param
=
new
SqlParameter[]
{
new
SqlParameter("@pic",
imgBytesIn)
}
DBHelper.GetExecuteQuery(sql,
param)第三步:
//将图片从数据库中取出
string
sql="select
*
from
pic
where
id=0"
SqlDataReader
reader
=
DBHelper.GetExecuteReader(sql,
null)
MemoryStream
mss
=
null
LZ,你想将图片保存到数据库中,有2中方法1:
最简单的,存图片地址,asp.net
中是
~\图片目录
2:
将整张图片保存到数据库中(将图片的副本保留到数据库),楼上的几个也说了,方法是可行的,但我就不知道
以流的方式读取后,能否还原图片,在MSsql
中没试过,但在Oracle
中,有Blog和Clog(应该没记错),可以保存任何数据(任何文件都可以保存),你试试
//把文件转成二进制流出入数据库
private void button2_Click(object sender, EventArgs e)
{
FileStream fs = new FileStream(textBox1.Text, FileMode.Open)
BinaryReader br = new BinaryReader(fs)
Byte[] byData = br.ReadBytes((int)fs.Length)
fs.Close()
string conn = "server=.database=testDBUid=saPwd=sa "
SqlConnection myconn = new SqlConnection(conn)
myconn.Open()
string str = "insert into pro_table (pro_name,pro_file) values('测试文件',@file)"
SqlCommand mycomm = new SqlCommand(str, myconn)
mycomm.Parameters.Add("@file", SqlDbType.Binary, byData.Length)
mycomm.Parameters["@file"].Value = byData
mycomm.ExecuteNonQuery()
myconn.Close()
}
//从数据库中把二进制流读出写入还原成文件
private void button4_Click(object sender, EventArgs e)
{
string conn = "server=.database=testDBUid=saPwd=sa "
string str = "select pro_file from pro_table where pro_name='测试文件' "
SqlConnection myconn = new SqlConnection(conn)
SqlDataAdapter sda = new SqlDataAdapter(str, conn)
DataSet myds = new DataSet()
myconn.Open()
sda.Fill(myds)
myconn.Close()
Byte[] Files = (Byte[])myds.Tables[0].Rows[0]["pro_file"]
BinaryWriter bw = new BinaryWriter(File.Open("D:\\2.rdlc",FileMode.OpenOrCreate))
bw.Write(Files)
bw.Close()
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)