標籤:
把圖片轉換成二進位--把二進位轉換成圖片
private void button1_Click(object sender, EventArgs e) { string path = this.textBox1.Text; byte[] imgBytesIn = SaveImage(path); ShowImgByByte(imgBytesIn); //Parameters.Add("@Photo", SqlDbType.Binary).Value = imgBytesIn; } //將圖片以二進位流 public byte[] SaveImage(String path) { FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read); //將圖片以檔案流的形式進行儲存 BinaryReader br = new BinaryReader(fs); byte[] imgBytesIn = br.ReadBytes((int)fs.Length); //將流讀入到位元組數組中 return imgBytesIn; } //現實二進位流代表的圖片 public void ShowImgByByte(byte[] imgBytesIn) { MemoryStream ms = new MemoryStream(imgBytesIn); pictureBox1.Image = Image.FromStream(ms); }
二、將圖片儲存到資料庫中,並從資料庫中讀取:
#region 將圖片從資料庫中讀取 /// <summary> /// 將圖片從資料庫中讀取 /// </summary> /// <param name="xs_ID">要讀取圖片的學號</param> /// <param name="ph">pictureBox1控制項名</param> public void get_photo(string xs_ID, PictureBox ph)//將圖片從資料庫中讀取 { byte[] imagebytes = null; getcon(); SqlCommand con = new SqlCommand("select * from S_jiben where S_num=‘" + xs_ID + "‘", link); SqlDataReader dr = con.ExecuteReader(); while (dr.Read()) { imagebytes =(byte[])dr.GetValue(18); } dr.Close(); con_close(); MemoryStream ms = new MemoryStream(imagebytes); Bitmap bmpt = new Bitmap(ms); ph.Image = bmpt; } #endregion #region public void SaveImage(string MID, 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); //將流讀入到位元組數組中 getcon(); StringBuilder strSql = new StringBuilder(); strSql.Append("update S_jiben Set [email protected] where S_num=" + MID); SqlCommand cmd = new SqlCommand(strSql.ToString(), link); cmd.Parameters.Add("@Photo", SqlDbType.Binary).Value = imgBytesIn; cmd.ExecuteNonQuery(); con_close(); } #endregion
結伴旅遊網www.jieberu.com
推推族,免費門票擷取平台 www.tuituizu.com
ASP.Net將圖片以二進位方式存入資料庫,並讀取