本實例主要介紹如何將圖片存入數據庫。將圖片存入數據庫,首先要在數據庫中建立一張表,將存儲圖片的字段類型設為Image類型,用FileStream類、BinaryReader把圖片讀成字節的形式,賦給一個字節數組,然后用ADO.SqlCommand對象的ExecuteNonQuery()方法來把數據保存到數據庫中。主要代碼如下:
??? private void button1_Click(object sender, EventArgs e)
??????? {
????????? openFileDialog1.Filter = "*jpg|*.JPG|*.GIF|*.GIF|*.BMP|*.BMP";
??????????? if(openFileDialog1.ShowDialog()==DialogResult.OK)
??????????? {
????????????? string fullpath =openFileDialog1.FileName;//文件路徑
????????????? FileStream fs = new FileStream(fullpath, FileMode.Open);
??????????????? byte[] imagebytes =new byte[fs.Length];
??????????????? BinaryReader br = new BinaryReader(fs);
??????????????? imagebytes = br.ReadBytes(Convert.ToInt32(fs.Length));
??????????????? //打開數據庫
??????????????? SqlConnection con = new SqlConnection("server=(local);uid=sa;pwd=;database=db_05");
??????????????? con.Open();
??????????????? SqlCommand com = new SqlCommand("insert into tb_08 values(@ImageList)",con);
??????????????? com.Parameters.Add("ImageList", SqlDbType.Image);
??????????????? com.Parameters["ImageList"].Value = imagebytes;
?????????????? com.ExecuteNonQuery();
?????????????? con.Close();
???????????? }????
}
本實例主要介紹如何從數據庫中把圖片讀出來。實現本實例主要是利用SqlDataReader從數據庫中把Image字段值讀出來,賦給一個byte[]字節數組,然后使用MemoryStream類與Bitmap把圖片讀取出來。主要代碼如下:
??? private void button1_Click(object sender, EventArgs e)
??????? {
???????????????? byte[] imagebytes = null;
??????????????? //打開數據庫
??????????? SqlConnection con = new SqlConnection("server=(local);uid=sa;pwd=;database=db_05");
??????????????? con.Open();
??????????????? SqlCommand com = new SqlCommand("select top 1* from tb_09", con);
??????????????? SqlDataReader dr = com.ExecuteReader();
??????????????? while (dr.Read())
??????????????? {
??????????????????? imagebytes = (byte[])dr.GetValue(1);
??????????????? }
??????????????? dr.Close();
??????????????? com.Clone();
??????????????? con.Close();
??????????????? MemoryStream ms = new MemoryStream(imagebytes);
??????????????? Bitmap bmpt = new Bitmap(ms);
??????????????? pictureBox1.Image = bmpt;
??????? }
本實例主要介紹如何只允許輸入指定圖片格式。用OpenFileDialog控件打開圖片文件,只要將OpenFileDialog控件的Filter屬性指定為特定的圖片格式即可。例如,打開.bmp文件的圖片,主要代碼如下:
this.openFileDialog1.Filter = "bmp文件(*.bmp)|*.bmp";
在用pictureBox控件輸入圖片時,要想統一圖片大小,只需把控件的SizeMode屬性值設為StretchImage即可,StretchImage值表示圖像的大小將調整為控件的大小。這樣,圖片的大小就統一了。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
