C#保存圖片到數據庫並讀取顯示圖片的方法


private void button2_Click_1(object sender, System.EventArgs e)

 

{sql

string pathName;數據庫

if (this.openFileDialog1.ShowDialog()==System.Windows.Forms.DialogResult.OK)數組

{ui

pathName = this.openFileDialog1.FileName;this

System.Drawing.Image img = System.Drawing.Image.FromFile(pathName);.net

this.pictureBox1.Image = img;code

//將圖像讀入到字節數組orm

System.IO.FileStream fs = new System.IO.FileStream(pathName,System.IO.FileMode.Open,System.IO.FileAccess.Read);圖片

byte[] buffByte = new byte[fs.Length];cmd

fs.Read(buffByte,0,(int)fs.Length);

fs.Close();

fs = null;

//創建Command命令

string comm = @"Insert into table1(img,name) values(@img,@name)";

this.sqlCommand1 = new System.Data.SqlClient.SqlCommand ();

this.sqlCommand1.CommandType = System.Data.CommandType.Text ;

this.sqlCommand1.CommandText = comm;

this.sqlCommand1.Connection = this.sqlConnection1 ;

//建立Parameter

this.sqlCommand1.Parameters.Add("@img",System.Data.SqlDbType.Image);

this.sqlCommand1.Parameters[0].Value = http://www.jb51.net/ianakin/archive/2012/02/02/buffByte;

this.sqlCommand1.Parameters.Add("@name",System.Data.SqlDbType.VarChar);

this.sqlCommand1.Parameters[1].Value =http://www.jb51.net/ianakin/archive/2012/02/02/pathName.Substring(pathName.LastIndexOf("\\")+1);

try

{

this.sqlConnection1.Open();

this.sqlCommand1.ExecuteNonQuery();

this.sqlConnection1.Close();

}

catch(System.Exception ee)

{

MessageBox.Show(ee.Message );

}

buffByte = null;

this.FillListBox();

}


讀取:

 

從數據庫讀圖片到picturebox


SqlConnection conn=new SqlConnection(@"data source=chenyuming2004VSdotNET;uid=sa;pwd=cym;database=lhf");

 

conn.Open();

SqlCommand cmd=new SqlCommand("select 照片 from fuser where password='1b'",conn);

SqlDataReader reader=cmd.ExecuteReader();

reader.Read();

MemoryStream buf=new MemoryStream((byte[])reader[0]);

Image image=Image.FromStream(buf,true);

pictureBox1.Image=image;

相關文章
相關標籤/搜索