//首先是如何把圖片和圖片的路徑存到資料庫
//呼叫ReadFile函式
byte[] imageData = ReadFile(放圖片的路徑字串);
//用的是本機的Window驗證
SqlConnection connect = new SqlConnection("Data Source=(local);Initial Catalog=放起始的資料庫是哪個; Integrated Security=True");
SqlCommand command = new SqlCommand("INSERT INTO dbo.MyTable(id,picture,picturepath) VALUES (1,@imageData,@imagePath)",connect);
//imageData是上面那個byte[] imageData
//textBox.text放的是圖片路徑
command.Parameters.Add(new SqlParameter("@imageData", (object)imageData));
command.Parameters.Add(new SqlParameter("@imagePath", (object)textBox.Text));
connect.Open();
command.ExecuteNonQuery();
connect.Close();
MessageBox.Show("圖片新增完成");
public byte[] ReadFile(string path)
{
byte[] data = null;
FileInfo fInfo = new FileInfo(path);
long length = fInfo.Length;
FileStream fStream = new FileStream(path, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fStream);
data = br.ReadBytes((int)length);
return data;
}
//取出圖片用路徑方式
SqlConnection connect = new SqlConnection("Data Source=(local);Initial Catalog=MyDB;Integrated Security=True");
SqlCommand command = new SqlCommand("SELECT picturepath FROM dbo.MyTable", connect);
connect.Open();
SqlDataReader dr = command.ExecuteReader();
//dr.Read()是開始讀進第一筆資料與持續讀到底
while (dr.Read())
{
string picturepath = dr[0].ToString();
byte[] imageData = ReadFile(picturepath);
using (MemoryStream ms = new MemoryStream(imageData))
{
pictureBox1.Image = Image.FromStream(ms);
MessageBox.Show("顯示成功");
}
}
connect.Close();
//取出圖片從資料庫方式
SqlConnection connect = new SqlConnection("Data Source=(local);Initial Catalog=MyDB;Integrated Security=True");
SqlCommand command = new SqlCommand("SELECT picture FROM dbo.MyTable", connect);
connect.Open();
SqlDataReader dr = command.ExecuteReader();
if (dr.Read())
{
//Get image data from gridview column.
//(這兩行註解留著或許以後會用到)
//byte[] imageData = (byte[])gridView2.GetDataRow(e.RowIndex)["picture"];
//byte[] imageData = (byte[])gridView2.Rows[e.RowIndex].Cells["picture"].Value;
byte[] imageData=(byte[])dr["picture"];
using (MemoryStream ms = new MemoryStream(imageData, 0, imageData.Length))
{
//這行註解留著或許以後會用到
//ms.Write(imageData, 0, imageData.Length);
pictureBox1.Image = Image.FromStream(ms);
}
connect.Close();
MessageBox.Show("顯示成功");
}
- Jun 30 Tue 2009 18:20
(C#)圖片用二進位Byte檔和用路徑方式存進與取出資料庫
全站熱搜
留言列表
發表留言