<1>將圖片轉換成二進制插入數據庫
FileStream fs = new FileStream("D:\\Add.ico",FileMode.Open);
byte[] imagebytes = new byte[fs.Length];
BinaryReader br = new BinaryReader(fs);
imagebytes = br.ReadBytes(Convert.ToInt32(fs.Length)); //將圖片轉換成二進制字符串
string s = "Data Source=A3135;Initial Catalog=mydb1;Integrated Security=True"; //連數據庫字符串
SqlConnection con = new SqlConnection(s);
con.Open();
string str = " insert into [picture](Line,Data) values(@Line,@Data)"; //插入picture表中字符串
SqlCommand cmd = new SqlCommand(str, con);
cmd.Parameters.AddWithValue("@Line", 1);
cmd.Parameters.AddWithValue("@Data", imagebytes); //將二進制流插入數據庫中
cmd.ExecuteNonQuery();
con.Close();
<2>將二進制還原爲圖片
MemoryStream ms = new MemoryStream(photo);
Bitmap bmpt = new Bitmap(ms); //將二進制流轉化成圖片格式
SickPicture.Image = bmpt; //SickPicture爲pictureBox控件名稱
<3>依據圖片路徑顯示圖片
Image image = Image.FromFile(PicturePath); //直接打開會出現再次添加時提示圖片資源佔用
Image bmp = new Bitmap(image);
SickPicture.Image = bmp;
image.Dispose();
<4>PictureBox綁定圖片的等比縮放
將pictureBox的SizeMode屬性設置爲StretchImage