SQL資料庫 二進制圖片如何導出成文件
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.1;Initial Catalog=TestDB;User ID=sa;Password=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.1;Initial Catalog=TestDB;User ID=sa;Password=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.1;Initial Catalog=TestDB;User ID=sa;Password=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控制項顯示從資料庫中讀出的二進制圖片
Ⅱ 如何從SQL資料庫中讀取二進制數據
讀出並生成圖片到物理位置
public void Read()
{
byte[] MyData = new byte[0];
using (SqlConnection conn = new SqlConnection(sqlconnstr))
{
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "select * from T_img";
SqlDataReader sdr = cmd.ExecuteReader();
sdr.Read();
MyData = (byte[])sdr["ImgFile"];//讀取第一個圖片的位流
int ArraySize= MyData.GetUpperBound(0);//獲得資料庫中存儲的位流數組的維度上限,用作讀取流的上限
FileStream fs = new FileStream(@"c:\00.jpg", FileMode.OpenOrCreate, FileAccess.Write);
fs.Write(MyData, 0, ArraySize);
fs.Close(); //-- 寫入到c:\00.jpg。
conn.Close();
Console.WriteLine("讀取成功");//查看硬碟上的文件
}
}