第一步:
/獲取當前選擇的圖片
this
.pictureBox1.Image = 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
;
if
(reader.Read())
{
byte
[] bytes = (
byte
[])reader[
"pic"
];
mss =
new
MemoryStream(bytes);
}
this
.pictureBox2.Image = Image.FromStream(mss);