
1.将图片以二进制存入数据库
//保存图片到数据库
protected void Button1_Click(object sender, EventArgs e)
{
//图片路径
string strPath = "~/photo/03.JPG"
string strPhotoPath = Server.MapPath(strPath)
//读取图片
FileStream fs = new System.IO.FileStream(strPhotoPath, FileMode.Open, FileAccess.Read)
BinaryReader br = new BinaryReader(fs)
byte[] photo = br.ReadBytes((int)fs.Length)
br.Close()
fs.Close()
//存入
SqlConnection myConn = new SqlConnection("Data Source=127.0.0.1Initial Catalog=TestDBUser ID=saPassword=sa")
string strComm = " INSERT INTO personPhoto(personName, personPhotoPath, personPhoto) "
strComm += " VALUES('wangwu', '" + strPath + "', @photoBinary )"
SqlCommand myComm = new SqlCommand(strComm, myConn)
myComm.Parameters.Add("@photoBinary", SqlDbType.Binary,photo.Length)
myComm.Parameters["@photoBinary"].Value = photo
myConn.Open()
myComm.ExecuteNonQuery()
myConn.Close()
}
2.读取二进制图片在页面显示
//读取图片
SqlConnection myConn = new SqlConnection("Data Source=127.0.0.1Initial Catalog=TestDBUser ID=saPassword=sa")
string strComm = " SELECT personPhoto FROM personPhoto WHERE personName='wangwu' "
SqlCommand myComm = new SqlCommand(strComm, myConn)
myConn.Open()
SqlDataReader dr = myComm.ExecuteReader()
while (dr.Read())
{
byte[] photo = (byte[])dr["personPhoto"]
this.Response.BinaryWrite(photo)
}
dr.Close()
myConn.Close()
或
SqlConnection myConn = new SqlConnection("Data Source=127.0.0.1Initial Catalog=TestDBUser ID=saPassword=sa")
SqlDataAdapter myda = new SqlDataAdapter(" SELECT personPhoto FROM personPhoto WHERE personName='11' ", myConn)
DataSet myds = new DataSet()
myConn.Open()
myda.Fill(myds)
myConn.Close()
byte[] photo = (byte[])myds.Tables[0].Rows[0]["personPhoto"]
this.Response.BinaryWrite(photo)
3.设置Image控件显示从数据库中读出的二进制图片
您好,我来为您解答:mage格式都转换了。所以直接从sqlserver 导出是得不到照片的。
利用前台程序,提取image格式的文件,然后转换成对应的照片。然后再导出。才能得到你要的效果。
前提,Image存的是照片对应的二进制文件!
如果我的回答没能帮助您,请继续追问。
编码格式问题吧看你写入数据库用的什么编码格式了
如果ASCII:
string info = System.Text.Encoding.ASCII.GetString(data )
如果UTF8:
string info = System.Text.Encoding.UTF8.GetString(data )
然后再把info写入文件中,就不用说了吧
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)