#region 用於在PictureBox控件中顯示選擇的圖片
/// <summary>
/// 用於在PictureBox控件中顯示選擇的圖片
/// </summary>
/// <param name="openF">圖像名</param>
/// <param name="MyImage">pictureBox控件ID</param>
public void Read_Image(OpenFileDialog openF, PictureBox MyImage)//顯示選擇的圖片
{
//指定OpenFileDialog控件打開的文件格式
openF.Filter = "*.jpg|*.jpg|*.bmp|*.bmp";
if (openF.ShowDialog()==DialogResult.OK)
{
try
{
//將圖片文件存入到PictureBox控件中
MyImage.Image = System.Drawing.Image.FromFile(openF.FileName);
}
catch (Exception)
{
//彈出錯誤信息
MessageBox.Show("您選擇的圖片不能被讀取或文件類型不對!","錯誤",MessageBoxButtons.OK,MessageBoxIcon.Warning);
throw;
}
}
}
#endregion
#region 用於將圖片以二進制形式存入數據庫中
/// <summary>
/// 用於將圖片以二進制形式存入數據庫中
/// </summary>
/// <param name="FilmID">影片ID</param>
/// <param name="openF"></param>
public void SaveImage(string FilmID, OpenFileDialog openF)//將圖片以二進制存入數據庫中
{
string strimg = openF.FileName.ToString(); //記錄圖片的所在路徑
FileStream fs = new FileStream(strimg, FileMode.Open, FileAccess.Read); //將圖片以文件流的形式進行保存
BinaryReader br = new BinaryReader(fs);
byte[] imgBytesIn = br.ReadBytes((int)fs.Length);//將流讀入到字節數組中
SqlConnection conn = sqlhelper.getcon();
conn.Open();
StringBuilder strSql = new StringBuilder();
strSql.Append("update T_Film Set F_FPhoto=@Photo where F_FId=" + FilmID);
SqlCommand cmd = new SqlCommand(strSql.ToString(), conn);
cmd.Parameters.Add("@Photo", SqlDbType.Binary).Value = imgBytesIn;
cmd.ExecuteNonQuery();
conn.Close();
}
#endregion
#region 用於將圖片從數據庫中取出並顯示在PictureBox控件中
/// <summary>
/// 用於將圖片從數據庫中取出並顯示在PictureBox控件中
/// </summary>
/// <param name="FilmID">影片ID</param>
/// <param name="pb">PictureBox控件ID</param>
public void Get_Image(string FilmID, PictureBox pb)//將圖片從數據庫中取出
{
byte[] imagebytes = null;
SqlConnection conn = sqlhelper.getcon();
conn.Open();
SqlCommand com = new SqlCommand("select * from T_Film where F_FId='" + FilmID + "'", conn);
SqlDataReader dr = com.ExecuteReader();
while (dr.Read())
{
imagebytes = (byte[])dr.GetValue(10);
}
dr.Close();
conn.Close();
MemoryStream ms = new MemoryStream(imagebytes);
Bitmap bmpt = new Bitmap(ms);
pb.Image = bmpt;
}
#endregion
上面三個分別為公共類,第一個為打開對話框,第二個為將圖像以二進制存入數據庫,第三個為從數據庫中讀取出來。
在窗體代碼中, Mymenu.Get_Image(FilmID, picboxPhoto);直接用就可以了(Mymenu)為公共類空間名稱
